Using TypeScript
Below is an array of objects & I want to map this in to a new object as provided below . (see the expected result)
// input array
const getPostAPI =
[
{
get: '1234',
post: 'abcd',
},
{
get: '3423',
post: 'dfcv',
},
{
get: '1234',
post: 'iucv',
},
{
get: '1234',
post: 'oipl',
},
{
get: '3423',
post: 'ffgf',
},
{
get: '4567',
post: 'tyui',
},
]
from the above array of objects I want to map the post values as an array for repeating get values. Below I've provided the exptected result.
// output object
const exptectedResult = {
'1234': ['abcd',
'iucv',
'oipl',
'1234',],
'3423': ['dfcv',
'ffgf'],
'4567': ['tyui']
}
Following is what I've tried. But it is overwriting some of the values. i.e., I'm not getting the exact number of elements in the array of corresponding get key. (it is one less than actual)
this.getPostMap = this.getPostAPI.reduce(
(map, api) => ({
...map,
[api.get]: map[api.get]
? [...map[api.get], api.post]
: [] || [],
}),
{}
);