【问题标题】:Combining two arrays of objects using Object.assign()?使用 Object.assign() 组合两个对象数组?
【发布时间】:2020-05-01 06:33:56
【问题描述】:

我不太清楚为什么 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' }
// ]

【问题讨论】:

  • 第二个 for 循环出现故障:for (let x = 0; x &lt; array_2.length; x++) {。缺少 length 属性。另一个问题是您修改了array_1 的元素,而不是您应该复制并分配新属性:Object.assign({}, array_1[i], array_2[x]);
  • @iY1NQ 非常感谢您注意到这一点;超级有帮助。但是现在输出仍然不是我所期望的。请参阅底部的更新代码和代码注释。具体来说,它没有输出 array_2[1]
  • @MarkBaijens 我更新了错字,但仍然没有产生预期的输出。
  • 您的代码仍然丢失Object.assign({}, array_1[i], array_2[x])。如果不先复制到空对象,您总是会覆盖array_1 的元素。
  • @iY1NQ 啊!抱歉,您第一次确实说过,我只是对丢失的 .length 感到过度兴奋。这解决了一切。谢谢!

标签: javascript arrays


【解决方案1】:

您可以使用 ... 扩展运算符合并对象。然后你会得到你想要的结果,因为你没有覆盖原始数组。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-04-22
    • 1970-01-01
    • 2019-06-10
    • 2021-03-08
    • 2019-12-02
    • 1970-01-01
    • 1970-01-01
    • 2022-01-04
    相关资源
    最近更新 更多