使用TypeScript
下面是对象数组,我想将此映射到下面提供的新对象。 (请参阅预期结果)
// 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',
},
]
从上面的对象数组中我想将发布值映射为重复获取值的数组。 下面提供了预期的结果。
// output object
const exptectedResult = {
'1234': ['abcd',
'iucv',
'oipl',
'1234',],
'3423': ['dfcv',
'ffgf'],
'4567': ['tyui']
}
以下是我尝试过的。但这正在覆盖某些价值。 也就是说,我没有在相应的获取键数组中获得确切数量的元素。 (比实际少一)
this.getPostMap = this.getPostAPI.reduce(
(map, api) => ({
...map,
[api.get]: map[api.get]
? [...map[api.get], api.post]
: [] || [],
}),
{}
);
答案 0 :(得分:1)
这段简单的代码将非常流畅地工作。
getPostAPI.reduce((acc, el)=>{
(acc[el.get] = acc[el.get] || []).push(el.post)
return acc
}, {})
答案 1 :(得分:1)
这是一个非常可怕且难以理解的代码块,它可以执行非常简单的操作。例如:
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',
},
];
const expectedResult = getPostAPI.reduce((map, {get,post}) =>
(map[get] = map[get] || []).push(post) && map,
{});
console.log(expectedResult);
答案 2 :(得分:0)
您的问题是,当未定义get属性时,您实际上想通过第一篇文章而不是一个空对象来实现它:
this.getPostMap = this.getPostAPI.reduce(
(map, api) => ({
...map,
[api.get]: map[api.get]
? [...map[api.get], api.post]
: [api.post],
}),
{}
);