让我们看一个例子。
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不适合我 它返回
$.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"}]
仅基于较新的Javascript的新版本,而无需任何第三方库。
const mergeByProperty = (target, source, prop) => { source.forEach(sourceElement => { let targetElement = target.find(targetElement => { return sourceElement[prop] === targetElement[prop]; }) targetElement ? Object.assign(targetElement, sourceElement) : target.push(sourceElement); }) } var target /* arr1 */ = [{name: "lang", value: "English"}, {name: "age", value: "18"}]; var source /* arr2 */ = [{name : "childs", value: '5'}, {name: "lang", value: "German"}]; mergeByProperty(target, source, 'name'); console.log(target)