Utilizing TypeScript
Here is an array containing objects that needs to be transformed into a new object as shown below. (refer to the expected outcome)
// sample input array
const getPostAPI =
[
{
get: '1234',
post: 'abcd',
},
{
get: '3423',
post: 'dfcv',
},
// more objects omitted for brevity
]
From the given array of objects, I aim to map the post values into an array for each repeating get value. The desired result is provided below.
// expected output object
const exptectedResult = {
'1234': ['abcd', 'iucv', 'oipl'],
'3423': ['dfcv'],
// more keys and values excluded for clarity
}
Below is the attempt made so far. However, some values are being overwritten. Specifically, the number of elements in the corresponding array for each get key is one less than it should be.
this.getPostMap = this.getPostAPI.reduce(
(map, api) => ({
...map,
[api.get]: map[api.get]
? [...map[api.get], api.post]
: [] || [],
}),
{}
);