合并 2 个对象数组

2022-08-30 01:51:38

让我们看一个示例。

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

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

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

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

是否有任何JavaScript或jQuery函数可以做到这一点?

$.extend不适合我。它返回

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

答案 1

如果你想在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

使用ES6,您可以非常轻松地完成,如下所示:

var arr1 = new Array({name: "lang", value: "German"}, {name: "age", value: "18"});
var arr2 = new Array({name : "childs", value: '5'}, {name: "lang", value: "German"});
var arr3 = [...arr1, ...arr2];

输出:

    arr3 = [
      {"name":"lang","value":"German"},
      {"name":"age","value":"18"},
      {"name":"childs","value":"5"},
      {"name":"lang","value":"German"}
    ]