我有以下两个数组
var arr1 = [
{
name: "abc"
},
{
name: "xyz"
}
];
var arr2 = [
{
age: 18
},
{
age: 21
}
];
我希望将上述数组像下面那样合并
arr3 = [
{
name:"abc",
age: 18
},
{
name:"xyz",
age: 21
}
];
我们将大力鼓励任何帮助
答案 0 :(得分:0)
如果只有两个数组,则可以使用对象传播运算符执行以下操作:
function combine(arr1, arr2) {
return arr1.map((obj, idx) => ({
...obj,
...arr2[idx]
}));
}
var arr1 = [
{
name: "abc"
},
{
name: "xyz"
}
];
var arr2 = [
{
age: 18
},
{
age: 21
}
];
console.log(combine(arr1, arr2));
如果您使用lodash,则可以使用_.merge
轻松完成此操作:
var arr1 = [
{
name: "abc"
},
{
name: "xyz"
}
];
var arr2 = [
{
age: 18
},
{
age: 21
}
];
console.log(_.merge(arr1, arr2));
<script src="https://unpkg.com/lodash@4.17.15/lodash.min.js"></script>