我有两个对象数组。如何将它们组合/合并为一个对象数组。
我尝试过使用concat函数以及遍历arr2并将其推入arr1中,但是我想用一种更短的方法来代替。
let arr1 = [{
_id: 1,
external_id: '74341f74-9c79-49d5-9611-87ef9b6eb75f',
name: 'Francisca Rasmussen',
alias: 'Miss Coffey'
},
{ _id: 19,
external_id: '68e35e26-7b1f-46ec-a9e5-3edcbcf2aeb9',
name: 'Francis Rodrigüez',
alias: 'Mr Lea'
},
{ _id: 23,
external_id: 'e9db9277-af4a-4ca6-99e0-291c8a97623e',
name: 'Francis Bailey',
alias: 'Miss Singleton'
}];
let arr2 = [ { organizations: 'Multron', joining_key: 1 },
{ organizations: 'Bitrex', joining_key: 19 },
{ organizations: 'Enthaze', joining_key: 23 },
{ tickets: 'A Nuisance in Kiribati', joining_key: 1 },
{ tickets: 'A Nuisance in Saint Lucia', joining_key: 19 }
{ tickets: 'A Nuisance in Saint Kilda', joining_key: 19 }
]
我想对它们进行连接,根据arr1上的_id字段的joining_key提供如下结果:
[{
_id: 1,
external_id: '74341f74-9c79-49d5-9611-87ef9b6eb75f',
name: 'Francisca Rasmussen',
alias: 'Miss Coffey',
organizations: 'Multron',
tickets: 'A Nuisance in Kiribati', joining_key: 1
},
{ _id: 19,
external_id: '68e35e26-7b1f-46ec-a9e5-3edcbcf2aeb9',
name: 'Francis Rodrigüez',
alias: 'Mr Lea',
organizations: 'Bitrex',
tickets: 'A Nuisance in Saint Lucia',
tickets: 'A Nuisance in Saint Kilda'
},
{ _id: 23,
external_id: 'e9db9277-af4a-4ca6-99e0-291c8a97623e',
name: 'Francis Bailey',
alias: 'Miss Singleton',
organizations: 'Enthaze'
}]
最佳答案
您可以在这种情况下使用Object.assign(...arr1)
在https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax处更多有关Spread运算符的参考
let arr1 = [{ _id: 1,
external_id: '74341f74-9c79-49d5-9611-87ef9b6eb75f',
name: 'Francisca Rasmussen',
alias: 'Miss Coffey',
created_at: '2016-04-15T05:19:46 -10:00'
}];
let arr2 = [ { organizations: 'Multron' },
{ tickets_1: 'A Nuisance in Kiribati' },
{ tickets_2: 'A Nuisance in Saint Lucia' }
];
arr1 = arr1.concat(arr2)
//console.log(arr1)
let result = [Object.assign(...arr1)]
console.log(result)
关于javascript - 合并对象数组,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/55544518/