This is a follow-up inquiry from: How can JavaScript convert multiple key-value pairs in object lists into one nested object?
The initial objective was to merge numerous objects with various key-value pairs into a single nested object.
For example, starting with 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 converting it to:
items = {
"toyota": {"wheel": 333, "shell": 350 },
"honda": {"wheel": 222, "shell": 250 }
}
The provided JavaScript code successfully achieves this:
const transformedItems = items.reduce((acc, item) => {
acc[item.mod] = { ...acc[item.mod], [item.part]: item.price }
return acc
}, {})
console.log(transformedItems)
Now, I am looking to implement this logic on the server-side using TypeScript, but encountering compilation errors:
/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 }
~~~~~~~~~~~~~
.
.
. (additional error lines omitted for brevity)
.
.
.
While investigating further, when executing:
const transformedItems = items.reduce((acc, item) => {
console.log(acc, item.mod) // log statement
acc[item.mod] = { ...acc[item.mod], [item.part]: item.price }
return acc
}, {})
The output from the console log displays normally: item.mod
being recognized as a string.
Why then does the compiler generate the error message about it being of type 'null'
?