3 回答
TA贡献2041条经验 获得超4个赞
如果要合并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"}]
TA贡献1780条经验 获得超1个赞
对于那些正在尝试现代事物的人:
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.find
function 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 functions
function 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-liner
var 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"
// }
// ]
TA贡献1842条经验 获得超21个赞
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);
添加回答
举报