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

我需要合并这2个对象数组并创build下面的数组。

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

有没有任何jScript或jQuery函数来做到这一点?

$ .extend不适合我。 它返回

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

先谢了,亚历山大。

 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); 

在这里输入图像说明

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

我总是从谷歌到这里,我总是不满意的答案。 你的回答很好,但是使用underscore.js会更容易,更整洁

DEMO: http : //jsfiddle.net/guya/eAWKR/

这是一个更一般的函数,它将使用对象的属性合并2个数组。 在这种情况下,该属性是“名称”

 var arr1 = [{name: "lang", value: "English"}, {name: "age", value: "18"}]; var arr2 = [{name : "childs", value: '5'}, {name: "lang", value: "German"}]; function mergeByProperty(arr1, arr2, prop) { _.each(arr2, function(arr2obj) { var arr1obj = _.find(arr1, function(arr1obj) { return arr1obj[prop] === arr2obj[prop]; }); arr1obj ? _.extend(arr1obj, arr2obj) : arr1.push(arr2obj); }); } mergeByProperty(arr1, arr2, 'name'); console.log(arr1); 

[{name:“lang”,value:“German”},{name:“age”,value:“18”},{name:“childs”,value:'5'}]

合并两个数组:

 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 result=arr1.concat(arr2); // result: [{name: "lang", value: "English"}, {name: "age", value: "18"}, {name : "childs", value: '5'}, {name: "lang", value: "German"}] 

合并两个数组而没有“name”的重复值:

 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 i,p,obj={},result=[]; for(i=0;i<arr1.length;i++)obj[arr1[i].name]=arr1[i].value; for(i=0;i<arr2.length;i++)obj[arr2[i].name]=arr2[i].value; for(p in obj)if(obj.hasOwnProperty(p))result.push({name:p,value:obj[p]}); // result: [{name: "lang", value: "German"}, {name: "age", value: "18"}, {name : "childs", value: '5'}] 

对于那些正在尝试现代事物的人来说:

 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" // } // ] 

您可以使用一个对象来收集您的属性,同时replace重复项,然后展开/展平该对象回到一个数组。 像这样的东西:

 function merge(args) { args = Array.prototype.slice.call(arguments); var o = { }; for(var i = 0; i < args.length; ++i) for(var j = 0; j < args[i].length; ++j) o[args[i][j].name] = args[i][j].value; return o; } function expand(o) { var a = [ ]; for(var p in o) if(o.hasOwnProperty(p)) a.push({ name: p, value: o[p]}); return a; } 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 = expand(merge(arr1, arr2)); 

我不知道这是否是最快的方法,但它适用于任何数量的input数组; 比如这个:

 var a = expand( merge( [{name: "lang", value: "English"}, {name: "age", value: "18"}], [{name: "childs", value: '5'}, {name: "lang", value: "German"}], [{name: 'lang', value: 'Pancakes'}] ) ); 

在“ arr3中用“German”代替“Pancakes”,给你带来同样的东西。

这种方法确实假设你的对象都具有相同的{name: ..., value: ...}forms。

你可以看到它在这里工作(请打开你的控制台): http : //jsfiddle.net/ambiguous/UtBbB/

另一个使用reduce() method版本:

 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 arr = arr1.concat(arr2).reduce(function(prev, current, index, array){ if(!(current.name in prev.keys)) { prev.keys[current.name] = index; prev.result.push(current); } else{ prev.result[prev.keys[current.name]] = current; } return prev; },{result: [], keys: {}}).result; document.getElementById("output").innerHTML = JSON.stringify(arr,null,2); 
 <pre id="output"/> 

最简单的方法是用一些ES6的魔法:

合并两个重复:

 const a = [{a: 1}, {b: 2}] const b = [{a: 1}] const result = a.concat(b) // [{a: 1}, {b: 2}, {a: 1}] 

没有重复它是一样的上面加上:

const distinct = [...new Set(result.map(item => item.YOUR_PROP_HERE))]

怎么样jQuery合并?

http://api.jquery.com/jQuery.merge/

这里的jsFiddle例子: http : //jsfiddle.net/ygByD/

我面临着同样的问题,基于古雅的答案,我已经扩展了下划线库,还增加了一些我需要的function。 这是Gist 。

 /** * Merges two object-like arrays based on a key property and also merges its array-like attributes specified in objectPropertiesToMerge. * It also removes falsy values after merging object properties. * * @param firstArray The original object-like array. * @param secondArray An object-like array to add to the firstArray. * @param keyProperty The object property that will be used to check if objects from different arrays are the same or not. * @param objectPropertiesToMerge The list of object properties that you want to merge. It all must be arrays. * @returns The updated original array. */ function merge(firstArray, secondArray, keyProperty, objectPropertiesToMerge) { function mergeObjectProperties(object, otherObject, objectPropertiesToMerge) { _.each(objectPropertiesToMerge, function (eachProperty) { object[eachProperty] = _.chain(object[eachProperty]).union(otherObject[eachProperty]).compact().value(); }); } if (firstArray.length === 0) { _.each(secondArray, function (each) { firstArray.push(each); }); } else { _.each(secondArray, function (itemFromSecond) { var itemFromFirst = _.find(firstArray, function (item) { return item[keyProperty] === itemFromSecond[keyProperty]; }); if (itemFromFirst) { mergeObjectProperties(itemFromFirst, itemFromSecond, objectPropertiesToMerge); } else { firstArray.push(itemFromSecond); } }); } return firstArray; } _.mixin({ merge: merge }); 

希望它是有用的! 问候!

我最近被这个问题困扰了,我来到了这里,希望能有一个答案,但是接受的答案使用了2个循环,我不喜欢。 我终于设法自己做了。 不依赖任何图书馆:

 function find(objArr, keyToFind){ var foundPos = objArr.map(function(ob){ return ob.type; }).indexOf(keyToFind); return foundPos; } function update(arr1,arr2){ for(var i = 0, len = arr2.length, current; i< len; i++){ var pos = find(arr1, arr2[i].name); current = arr2[i]; if(pos !== -1) for(var key in arr2) arr1[pos][key] = arr2[key]; else arr1[arr1.length] = current; } } 

这也保持了arr1的顺序。

用lodash:

 _.uniqBy([...arr1, ...arr2], 'name') 

closures我的头顶 – 尝试jQuery扩展

 var arr3 = jQuery.extend(arr1,arr2....) 

var newArray = yourArray.concat(otherArray); console.log('Concatenated newArray: ', newArray);

基于@你的答案,但保持秩序:

 var arr3 = []; for(var i in arr1){ var shared = false; for (var j in arr2) if (arr2[j].name == arr1[i].name) { arr3.push(arr1[j] shared = true; break; } if(!shared) arr3.push(arr1[i]) } for(var j in arr2){ var shared = false; for (var i in arr1) if (arr2[j].name == arr1[i].name) { shared = true; break; } if(!shared) arr3.push(arr2[j]) } arr3 

我知道这个解决scheme的效率不高,但是如果你想保持顺序并且仍然更新对象,这是必要的。

这是我写的一个jQuery插件,通过一个键合并两个对象数组。 请记住,这会就地修改目标数组。

 (function($) { $.extendObjectArray = function(destArray, srcArray, key) { for (var index = 0; index < srcArray.length; index++) { var srcObject = srcArray[index]; var existObject = destArray.filter(function(destObj) { return destObj[key] === srcObject[key]; }); if (existObject.length > 0) { var existingIndex = destArray.indexOf(existObject[0]); $.extend(true, destArray[existingIndex], srcObject); } else { destArray.push(srcObject); } } return destArray; }; })(jQuery); var arr1 = [ { name: "lang", value: "English" }, { name: "age", value: "18" } ]; var arr2 = [ { name: "childs", value: '5' }, { name: "lang", value: "German" } ]; var arr3 = $.extendObjectArray(arr1, arr2, 'name'); console.log(JSON.stringify(arr3, null, 2)); 
 .as-console-wrapper { top: 0; max-height: 100% !important; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 

使用lodash你想_.uniqBy

 var arr3 = _.uniqBy(arr1.concat(arr2), 'name'); // es5 let arr3 = _.uniqBy([...arr1, ...arr2], 'name'); // es6 

arr1,arr2的顺序很重要!

看文档https://lodash.com/docs/4.17.4#uniqBy