合并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"});


Cats萌萌
浏览 1716回答 3
3回答

缥缈止盈

如果要合并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"}]

慕神8447489

对于那些正在尝试现代事物的人:var odd = [    { name : "1", arr: "in odd" },    { name : "3", arr: "in odd" }];var even = [    { name : "1", arr: "in even" },    { name : "2", arr: "in even" },    { name : "4", arr: "in even" }];// ----// ES5 using Array.filter and Array.findfunction merge(a, b, prop){  var reduced = a.filter(function(aitem){      return ! b.find(function(bitem){          return aitem[prop] === bitem[prop];      });  });  return reduced.concat(b);}console.log( "ES5", merge(odd, even, "name") );// ----// ES6 arrow functionsfunction merge(a, b, prop){    var reduced =  a.filter( aitem => ! b.find ( bitem => aitem[prop] === bitem[prop]) )  return reduced.concat(b);}console.log( "ES6", merge(odd, even, "name") );// ----// ES6 one-linervar merge = (a, b, p) => a.filter( aa => ! b.find ( bb => aa[p] === bb[p]) ).concat(b);console.log( "ES6 one-liner", merge(odd, even, "name") );// Results// ( stuff in the "b" array replaces things in the "a" array )// [//    {//         "name": "3",//         "arr": "in odd"//     },//     {//         "name": "1",//         "arr": "in even"//     },//     {//         "name": "2",//         "arr": "in even"//     },//     {//         "name": "4",//         "arr": "in even"//     }// ]

茅侃侃

var arr3 = [];for(var i in arr1){   var shared = false;   for (var j in arr2)       if (arr2[j].name == arr1[i].name) {           shared = true;           break;       }   if(!shared) arr3.push(arr1[i])}arr3 = arr3.concat(arr2);
打开App,查看更多内容
随时随地看视频慕课网APP