我有两个数组。第一个数组是:
arrayOne = [
{id: 1, type: 'Animal', legs: 4},
{id: 2, type: 'Animal', legs: 2},
{id: 3, type: 'Animal', legs: 8},
{id: 4, type: 'Plant', legs: 0},
]
这是第二个数组:
arrayTwo = [
{typeId: 1, processing: 2},
{typeId: 1, processing: 3},
{typeId: 1, approved: 3},
{typeId: 1, approved: 2},
{typeId: 1, disapproved: 3},
{typeId: 1, disapproved: 2},
{typeId: 2, approved: 2},
{typeId: 2, disapproved: 1},
{typeId: 2, disapproved: 1},
{typeId: 3, approved: 2},
{typeId: 4, disapproved: 3},
]
如果arrayOne的id等于arrayTwo的typeId,则将arrayTwo追加到arrayOne中,并将批准和不批准的处理数相加。这是我想要的数组:
desiredArray = [
{id: 1, type: 'Animal', legs: 4, processing: 5, approved: 5, disapproved: 5},
{id: 2, type: 'Animal', legs: 2, approved: 2, disapproved: 2},
{id: 3, type: 'Animal', legs: 8, approved: 2},
{id: 4, type: 'Plant', legs: 0, disapproved: 3},
]
您可以先reduce
第二个数组,然后map
到第一个数组:
const arrayOne = [{id: 1, type: 'Animal', legs: 4},{id: 2, type: 'Animal', legs: 2},{id: 3, type: 'Animal', legs: 8},{id: 4, type: 'Plant', legs: 0},];
const arrayTwo = [{typeId: 1, processing: 2},{typeId: 1, processing: 3},{typeId: 1, approved: 3},{typeId: 1, approved: 2},{typeId: 1, disapproved: 3},{typeId: 1, disapproved: 2},{typeId: 2, approved: 2},{typeId: 2, disapproved: 1},{typeId: 2, disapproved: 1},{typeId: 3, approved: 2},{typeId: 4, disapproved: 3},];
const reduced = arrayTwo.reduce((a,{typeId, ...rest})=>{
a[typeId] ??= {};
Object.entries(rest).forEach(([k,v])=>{
a[typeId][k] ??= 0;
a[typeId][k]+=v;
});
return a;
},{});
const result = arrayOne.map(o=>({...o, ...reduced[o.id]}));
console.log(result);
让我为你编码。
arrayOne = [{
id: 1,
type: 'Animal',
legs: 4
},
{
id: 2,
type: 'Animal',
legs: 2
},
{
id: 3,
type: 'Animal',
legs: 8
},
{
id: 4,
type: 'Plant',
legs: 0
},
]
arrayTwo = [{
typeId: 1,
processing: 2
},
{
typeId: 1,
processing: 3
},
{
typeId: 1,
approved: 3
},
{
typeId: 1,
approved: 2
},
{
typeId: 1,
disapproved: 3
},
{
typeId: 1,
disapproved: 2
},
{
typeId: 2,
approved: 2
},
{
typeId: 2,
disapproved: 1
},
{
typeId: 2,
disapproved: 1
},
{
typeId: 3,
approved: 2
},
{
typeId: 4,
disapproved: 3
},
]
for (let x in arrayOne) {
for (let y of arrayTwo) {
if(arrayOne[x].id == y.typeId){
arrayOne[x] = {...arrayOne[x], ...y};
}
}
}
console.log(arrayOne)