I have a series of TypeScript objects structured like this:
interface MyObject {
id: string,
position: number
}
My goal is to transform this array into a map format where it shows the relationship between id and position, as needed for a future JSON POST request:
{
"id1": 1,
"id2": 2,
}
One option is utilizing an ES6 Map
:
array.reduce((map, obj) => map.set(obj.id, obj.position), new Map())
This method works well, but converting an ES6 Map
to JSON can be tricky.
I've attempted to convert the key-value pairs into a plain object using various strategies such as Indexable Types, Object.create({})
, and other approaches, but TypeScript doesn't seem to agree with any of my attempts.
How can I efficiently extract a pure object literal containing key-value pairs from an array of objects?