合并 JavaScript 中具有相同键的两个对象数组

Merge two arrays of objects with the same keys in JavaScript

我想合并这两个数组

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.

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

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

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

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

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

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