使用Object.assign()合并两个对象数组?

4

我不太确定为什么 Object.assign() 没有提供预期的结果(请参见底部的注释部分)。我是否在函数中遗漏了什么,或者有更简洁的方法来实现这个功能?

下面的代码可以到达变量“i”的 for 循环,但无法到达变量“x”的第二个 for 循环。

    const array_1 = [{property1:'a',property2:'b'}, {property1:'c',property2:'d'}];
const array_2 = [{property3:'w',property4:'x'}, {property3:'y',property4:'z'}];

const CombineArrays = (array_1, array_2) => {
  let combined_array = [];
  for (let i = 0; i < array_1.length; i++) {
    for (let x = 0; x < array_2.length; x++) {
      const newObj = Object.assign(array_1[i], array_2[x]);
      combined_array.push(newObj);
    }
  }
  return combined_array;
};

const result = CombineArrays(array_1, array_2);
console.log(result);


// expected result = [
//     {property1:'a',property2:'b', property3:'w',property4:'x'},
//     {property1:'a',property2:'b', property3:'y',property4:'z'},
//     {property1:'c',property2:'d', property3:'w',property4:'x'},
//     {property1:'c',property2:'d', property3:'y',property4:'z'}
// ]
// current result = [
//     { property1: 'a', property2: 'b', property3: 'y', property4: 'z' },
//     { property1: 'a', property2: 'b', property3: 'y', property4: 'z' },
//     { property1: 'c', property2: 'd', property3: 'y', property4: 'z' },
//     { property1: 'c', property2: 'd', property3: 'y', property4: 'z' }
// ]


4
第二个 for 循环中存在错误:for (let x = 0; x < array_2.length; x++) {length 属性缺失。另一个问题是您修改了 array_1 的元素,而应该制作一份拷贝并分配新属性:Object.assign({}, array_1[i], array_2[x]); - iY1NQ
@iY1NQ 非常感谢您的注意和帮助。但是现在输出仍然不符合我的预期。请查看底部更新的代码和代码注释。具体来说,它没有输出array_2[1]。 - mpc75
@MarkBaijens,我更正了错别字,但它仍然没有产生预期的输出。 - mpc75
1
你的代码仍然缺少 Object.assign({}, array_1[i], array_2[x])。如果不先将其复制到一个空对象中,你总是会覆盖 array_1 的元素。 - iY1NQ
@iY1NQ 哎呀!对不起,你第一次就说过了,我只是被缺少的 .length 弄得太兴奋了。这个修复了所有问题。谢谢你! - mpc75
1个回答

0

你可以使用...展开运算符合并对象。这样,你就可以得到你想要的结果,因为你不会覆盖原始数组。

const array_1 = [{property1:'a',property2:'b'}, {property1:'c',property2:'d'}];
const array_2 = [{property3:'w',property4:'x'}, {property3:'y',property4:'z'}];

const CombineArrays = (array_1, array_2) => {
  let combined_array = [];
  for (let i = 0; i < array_1.length; i++) {
    for (let x = 0; x < array_2.length; x++) {
      const newObj = {...array_1[i], ...array_2[x]};
      combined_array.push(newObj);
    }
  }
  return combined_array;
};

const result = CombineArrays(array_1, array_2);
console.log(result);


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接