如何结合以下两个JavaScript数组对象:
对象数组1
[{id:1,name:alan}, {id:3,name:alice}]
对象数组2
[{id:4,name:sam}, {id:6,name:ella}]
所需
[{id:1,name:alan}, {id:3,name:alice},
{id:4,name:sam}, {id:6,name:ella}]
答案 0 :(得分:2)
您可以使用concat
来实现:
const objectArray1 = [{id:1,name:'alan'}, {id:3,name:'alice'}]
const objectArray2 = [{id:4,name:'sam'}, {id:6,name:'ella'}]
const desired = [].concat(objectArray1, objectArray2)
console.log(desired)
与其他方法(即依赖于现代语法/语言功能)相比,这种方法的一个优势是兼容性更高。
有关concat
,see the documentation for this method on the Array type at MDN
答案 1 :(得分:1)
您可以使用扩展运算符...
。
如果alan
,alice
等不是变量,您也需要将其放在引号中
let obj1 = [{
id: 1,
name: 'alan'
}, {
id: 3,
name: 'alice'
}]
let obj2 = [{
id: 4,
name: 'sam'
}, {
id: 6,
name: 'ella'
}]
let obj3 = [...obj1, ...obj2];
console.log(obj3)
答案 2 :(得分:0)
var array1 = ['a', 'b', 'c'];
var array2 = ['d', 'e', 'f'];
console.log(array1.concat(array2));
// expected output: Array ["a", "b", "c", "d", "e", "f"]
答案 3 :(得分:0)
作为Array.prototype.concat
的替代方法,可以使用ES6 spread syntax。
const a = [{
id: 1,
name: 'alan'
}, {
id: 3,
name: 'alice'
}];
const b = [{
id: 4,
name: 'sam'
}, {
id: 6,
name: 'ella'
}];
const c = [...a, ...b];
console.log(c);