Node.js 在Typescript中嵌套键的对象的组数组
我有一个对象数组,其中这些对象可以具有相同的名称,每个对象都有一个作为数组的错误键Node.js 在Typescript中嵌套键的对象的组数组,node.js,typescript,Node.js,Typescript,我有一个对象数组,其中这些对象可以具有相同的名称,每个对象都有一个作为数组的错误键 const array = [ { name: 'Rafael', errors: [ 1, 2 ] }, { name: 'Rafael', errors: [7] }, { name: 'Joao', errors: [ 8 ] } ] 我试图得到这样的回答: const response = [ { name: 'Rafa
const array = [
{
name: 'Rafael',
errors: [ 1, 2 ]
},
{
name: 'Rafael',
errors: [7]
},
{
name: 'Joao',
errors: [ 8 ]
}
]
我试图得到这样的回答:
const response = [
{
name: 'Rafael',
errors: [ 1, 2, 7]
}, {
name: 'Joao',
errors: [8]
}
]
有人知道怎么做吗?我尝试使用lodash的groupBy,但我无法得到响应,我想你可以用一个简单的而不是lodash,如下所示:
const array = [
{
name: 'Rafael',
errors: [ 1, 2 ]
},
{
name: 'Rafael',
errors: [7]
},
{
name: 'Joao',
errors: [ 8 ]
}
]
const newArray = array.reduce((list, item) => {
const {name, errors} = item;
const nameIndex = list.findIndex(item => item.name === name);
if(nameIndex === -1){
list.push(item);
} else {
list[nameIndex].errors.push(errors)
}
return list
}, []);
你也可以在家里试试