【问题标题】:Merge objects in arrays合并数组中的对象
【发布时间】:2017-01-17 19:02:30
【问题描述】:

我有两个数组:

[{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"}]

对此的任何帮助将不胜感激

【问题讨论】:

标签: javascript arrays javascript-objects


【解决方案1】:

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);

【讨论】:

  • 将 .hasOwnProperty() 检查添加到您的解决方案中,这很好。
  • 为什么?请解释一下。
  • 有内部属性的可能性。你是对的。
【解决方案2】:

这是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);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多