【问题标题】:Merge two arrays of objects with the same keys in JavaScript [closed]在JavaScript中合并两个具有相同键的对象数组[关闭]
【发布时间】:2021-10-21 09:25:01
【问题描述】:

我想合并这两个数组

const arr1 = [{ label: 'one', value: 'one', type: 'arr1'}];
const arr2 = [{ label: 'two', value: 'two', type: 'arr1'}];

得到以下结果

const arr3 = [{ label: 'one', value: 'one' type: 'arr1'}, { label: 'two', value: 'two' type: 'arr1'}];

我试过arr1.concat(arr2)_.merge(arr1, arr2)[arr1, arr2]得到以下错误

TypeError: Invalid attempt to spread non-iterable instance.
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.

【问题讨论】:

  • type 之前缺少逗号,使其语法无效
  • 如果您修复了语法错误,您将不会收到错误消息(至少对于 .conat()[arr1, arr2] 不会)。所以... -> How do I ask a good question? -> minimal reproducible example
  • 在我的代码中,我有逗号,这只是我为这个问题编写一些虚拟代码时的一个错误。感谢您指出。
  • 这能回答你的问题吗? Merge 2 arrays of objects

标签: javascript arrays javascript-objects


【解决方案1】:

您的第三次尝试[arr1, arr2] 非常接近正确答案,您可以使用新的扩展语法(...) 通过执行以下操作来连接数组:

const arr1 = [{ label: "one", value: "one", type: "arr1" }];
const arr2 = [{ label: "two", value: "two", type: "arr1" }];

console.log([...arr1, ...arr2]);

【讨论】:

    【解决方案2】:

    你可以试试这段代码,它工作正常:

     const arr1 = [{ label: 'one', value: 'one', type: 'arr1'}];
            const arr2 = [{ label: 'two', value: 'two', type: 'arr1'}];
            const arr3 = arr1.concat(arr2);
            
            console.log(arr3);

    【讨论】:

      【解决方案3】:

      你在type之前漏掉了逗号

      但你可以这样解决。

      const arr1 = [{ label: 'one', value: 'one', type: 'arr1'}];
      const arr2 = [{ label: 'two', value: 'two', type: 'arr1'}];
      
      const arr3 = arr1.concat(arr2);
      
      console.log(arr3);

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-01-13
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多