首页 > 解决方案 > 将两个数组元素合并为一个元素

问题描述

我正在尝试以下列方式组合两个数组。

var x = [{'d1':'3'}, {{'d2':'4'}}, {{'d3':'5'}}]
var y = [{'c1':'3'}, {{'c2':'4'}}, {{'c3':'5'}}]

我的结果应该是这样的

z = [
{'d1':'3', 'c1':'3' },
{'d1':'4', 'c1':'4' },
{'d1':'5', 'c1':'5' },
]

标签: javascript

解决方案


清理你的语法,这就是我最终的结果:

let x = [{d1:'3'}, {d2:'4'}, {d3:'5'}];
let y = [{c1:'3'}, {c2:'4'}, {c3:'5'}];

// create a new list to store the objects we'll create
let z = [];

[x, y].forEach(array => {
  // loop through the values for this line
  for (i=0; i < array.length; i++) {
    // handle case where we need to add more objects to our list
    if (z.length <= i) z.push({});
    // add new kay and value
    z[i][Object.keys(array[i])[0]] = array[i][Object.keys(array[i])[0]];
  }
});

console.log(z)

请注意,通过更改[x,y]为更多列表(例如[x,y,z,w]此代码),假设它们的大小都相同,它们仍然可以工作:)

在此处查看实时示例。


推荐阅读