合并2个对象数组

让我们看一个例子。

var arr1 = new Array({name: "lang", value: "English"}, {name: "age", value: "18"});

var arr2 = new Array({name : "childs", value: '5'}, {name: "lang", value: "German"});

我需要合并这两个对象数组并创建以下数组:

arr3 = new Array({name: "lang", value: "German"}, {name: "age", value: "18"}, {name : "childs", value: '5'});

有没有JavaScript或jQuery函数可以做到这一点?

$.extend不适合我 它返回

arr4 = new Array({name : "childs", value: '5'}, {name: "lang", value: "German"});

回答:

如果要在JavaScript中合并2个对象数组。你可以使用这一招

Array.prototype.push.apply(arr1,arr2);

例如

var arr1 = [{name: "lang", value: "English"},{name: "age", value: "18"}];

var arr2 = [{name : "childs", value: '5'}, {name: "lang", value: "German"}];

Array.prototype.push.apply(arr1,arr2);

console.log(arr1); // final merged result will be in arr1

输出:

[{"name":"lang","value":"English"},

{"name":"age","value":"18"},

{"name":"childs","value":"5"},

{"name":"lang","value":"German"}]

以上是 合并2个对象数组 的全部内容, 来源链接: utcz.com/qa/427425.html

回到顶部