合并数组中的对象

时间:2016-09-09 15:15:13

标签: javascript arrays javascript-objects

我有两个数组:

[{Name: "Jack", Depot: "5"}, {Name: "Jill", Depot: "6"}]

[{Depot Name: "Edgware"}, {Depot Name: "Romford"}]

我需要从第二个数组中取出对象并将它们与第一个数组中的对象合并,以产生以下结果:

[{Name: "Jack", Depot: "5", Depot Name: "Edgware"}, {Name: "Jill", Depot: "6", Depot Name: "Romford"}]

非常感谢任何帮助

2 个答案:

答案 0 :(得分:6)



var array1 = [{
  Name: "Jack",
  Depot: "5"
}, {
  Name: "Jill",
  Depot: "6"
}];
var array2 = [{
  'Depot Name': "Edgware"
}, {
  'Depot Name': "Romford"
}];

for (var a in array1) {
  for (var p in array1[a]) {
    //to esclude all possible internal properties
    if (array1[a].hasOwnProperty(p)) {
	 array2[a][p] = array1[a][p];
    }
  }
}

console.log(array2);




答案 1 :(得分:1)

以下是Object.assign()的解决方案。

P.S:检查浏览器兼容性,此解决方案可能无法在IE中使用

var arr1 = [{
  "Name": "Jack",
  "Depot": "5"
}, {
  "Name": "Jill",
  "Depot": "6"
}];

var arr2 = [{
  "Depot Name": "Edgware"
}, {
  "Depot Name": "Romford"
}];

var arr1Copy = arr1;
var newArr = arr1Copy.map(function(v, i) {
  return Object.assign(v, arr2[i]);
});

console.log(newArr);