This is a follow-up question to: Javascript: How to convert a list of objects with many key-value pairs into one big nested object?
The original goal was to convert a list of objects with many key-value pairs into one big nested object.
for example, from this:
const items = [
{
"id": 3,
"orgId": 2,
"mod": "toyota",
"part": "wheel",
"price": 333
},
{
"id": 4,
"orgId": 2,
"mod": "toyota",
"part": "shell",
"price": 350
},
{
"id": 9,
"orgId": 2,
"mod": "honda",
"part": "wheel",
"price": 222
},
{
"id": 10,
"orgId": 2,
"mod": "honda",
"part": "shell",
"price": 250
}
]
and convert to:
items = {
"toyota": {"wheel": 333, "shell": 350 },
"honda": {"wheel": 222, "shell": 250 }
}
The following code works in Javascript:
const transformedItems = items.reduce((acc, item) => {
acc[item.mod] = { ...acc[item.mod], [item.part]: item.price }
return acc
}, {})
console.log(transformedItems)
How, I want to put this logic to server-side (written in Typescript), and the code does not compile:
/Users/john/tmp/dolphin/api/node_modules/ts-node/src/index.ts:293
return new TSError(diagnosticText, diagnosticCodes)
^
TSError: ⨯ Unable to compile TypeScript:
src/utils/billingFunctions.ts:52:11 - error TS2538: Type 'null' cannot be used as an index type.
52 acc[item.mod] = { ...acc[item.mod], [item.part]: item.price }
~~~~~~~~~~~~~
src/utils/billingFunctions.ts:52:37 - error TS2538: Type 'null' cannot be used as an index type.
52 acc[item.mod] = { ...acc[item.mod], [item.part]: item.price }
~~~~~~~~~~~~~
src/utils/billingFunctions.ts:52:53 - error TS2464: A computed property name must be of type 'string', 'number', 'symbol', or 'any'.
52 acc[item.mod] = { ...acc[item.mod], [item.part]: item.price }
~~~~~~~~~~~~~~~
at createTSError (/Users/john/tmp/dolphin/api/node_modules/ts-node/src/index.ts:293:12)
at reportTSError (/Users/john/tmp/dolphin/api/node_modules/ts-node/src/index.ts:297:19)
at getOutput (/Users/john/tmp/dolphin/api/node_modules/ts-node/src/index.ts:399:34)
at Object.compile (/Users/john/tmp/dolphin/api/node_modules/ts-node/src/index.ts:457:32)
at Module.m._compile (/Users/john/tmp/dolphin/api/node_modules/ts-node/src/index.ts:530:43)
at Module._extensions..js (internal/modules/cjs/loader.js:1092:10)
at Object.require.extensions.<computed> [as .ts] (/Users/john/tmp/dolphin/api/node_modules/ts-node/src/index.ts:533:12)
at Module.load (internal/modules/cjs/loader.js:928:32)
at Function.Module._load (internal/modules/cjs/loader.js:769:14)
at Module.require (internal/modules/cjs/loader.js:952:19)
[nodemon] app crashed - waiting for file changes before starting...
However, when I try:
const transformedItems = items.reduce((acc, item) => {
console.log(acc, item.mod) // print out
acc[item.mod] = { ...acc[item.mod], [item.part]: item.price }
return acc
}, {})
The console log prints normally: item.mod
is a string.
How come it complains that it is Type 'null'
?