对象分配合并2个对象数组并保持自身属性

时间:2017-08-11 08:39:07

标签: javascript ecmascript-6

我尝试使用Object assign合并2个对象数组。我知道我可以通过比较他们的ID来做地图,但不知何故没有在object.assign中工作?

const ageArr = [{
  "id": 1,
  "age_range": "0 - 10 Years old",
  "value": 1
}, {
  "id": 2,
  "age_range": "11 - 20 Years old",
  "value": 1
}, {
  "id": 3,
  "age_range": "21 - 30 Years old",
  "value": 78
}]

const colorArr = [{
  "id": 1,
  "color": "#333"
}, {
  "id": 2,
  "color": "#666"
}, {
  "id": 3,
  "color": "#999"
}]

const mergedArr = Object.assign({}, ageArr, colorArr)
console.log(mergedArr)

https://jsfiddle.net/u6L2ceux

1 个答案:

答案 0 :(得分:-1)

如果您只想将两个数组添加到一个数组中,您可以尝试这样做:



const ageArr = [{
  "id": 1,
  "age_range": "0 - 10 Years old",
  "value": 1
}, {
  "id": 2,
  "age_range": "11 - 20 Years old",
  "value": 1
}, {
  "id": 3,
  "age_range": "21 - 30 Years old",
  "value": 78
}]

const colorArr = [{
  "id": 1,
  "color": "#333"
}, {
  "id": 2,
  "color": "#666"
}, {
  "id": 3,
  "color": "#999"
}]

const mergedArr = ageArr.concat(colorArr)
console.log(mergedArr)




请记住,concat函数确实返回一个新数组,并且不会对任何其他数组进行任何更改。含义colorArr和ageArr在concat()调用后没有变化。

看看文档: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/concat