合并2个对象数组

时间:2011-08-22 10:37:17

标签: javascript jquery arrays

让我们看一个例子。

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

我需要合并这2个对象数组并创建以下数组。

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

提前致谢, 亚历山大。

40 个答案:

答案 0 :(得分:54)

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

答案 1 :(得分:27)

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

enter image description here

答案 2 :(得分:26)

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

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

答案 3 :(得分:18)

我总是从谷歌来到这里,我总是不满意答案。你的回答很好但是使用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'}]

答案 4 :(得分:15)

合并两个数组:

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'}]

答案 5 :(得分:13)

使用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"}
    ]

答案 6 :(得分:11)

最简单的方法是使用一些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))]

答案 7 :(得分:7)

使用ES6传播算子非常简单:

$Dname = "select Dname from Instructor_Works where IID = '$id[2]'";

$sql = "insert into Enrolls (MID, Cnum, Dname) values ('$MID', '$ids[2]', '$Dname' )";
const array1 = [{a: 'HI!'}, {b: 'HOW'}]
const array2 = [{c: 'ARE'}, {d: 'YOU?'}]

const mergedArray = [ ...array1, ...array2 ]
console.log('Merged Array: ', mergedArray)

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

答案 8 :(得分:6)

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

&#13;
&#13;
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);    
&#13;
<pre id="output"/>
&#13;
&#13;
&#13;

答案 9 :(得分:6)

用lodash:

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

答案 10 :(得分:5)

我会合并两个具有重复项的数组,然后使用我的 this answer 删除重复项。这看起来是最短的路。

const arr1 = [{
    name: "lang",
    value: "English"
  },
  {
    name: "age",
    value: "18"
  }
];

const arr2 = [{
    name: "childs",
    value: '5'
  },
  {
    name: "lang",
    value: "German"
  }
];

const mergedArray = [...arr1, ...arr2];
const uniqueData = [...mergedArray.reduce((map, obj) => map.set(obj.name, obj), new Map()).values()];

console.log(uniqueData)

答案 11 :(得分:5)

这就是我在ES6环境中解决类似问题的方法:

function merge(array1, array2, prop) {
    return array2.map(function (item2) {
        var item1 = array1.find(function (item1) {
            return item1[prop] === item2[prop];
        });
        return Object.assign({}, item1, item2);
    });
}

注意:此方法不会返回array1中未出现在array2中的任何项目。

编辑:我有一些情况我想保留第二个数组中没有出现的项目,所以我提出了另一种方法。

function mergeArrays(arrays, prop) {
    const merged = {};

    arrays.forEach(arr => {
        arr.forEach(item => {
            merged[item[prop]] = Object.assign({}, merged[item[prop]], item);
        });
    });

    return Object.values(merged);
}

var arr1 = [
    { name: 'Bob', age: 11 },
    { name: 'Ben', age: 12 },
    { name: 'Bill', age: 13 },
];

var arr2 = [
    { name: 'Bob', age: 22 },
    { name: 'Fred', age: 24 },
    { name: 'Jack', age: 25 },
    { name: 'Ben' },
];

console.log(mergeArrays([arr1, arr2], 'name'));

答案 12 :(得分:4)

您可以使用对象收集属性,同时替换重复项,然后将该对象展开/展平回数组。像这样:

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

我不知道这是否是最快的方法,但它适用于任意数量的输入数组;例如,这个:

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

a arr3中的“{1}},”德语“替换为”煎饼“,为您提供相同的内容。

这种方法确实假设您的对象当然都具有相同的{name: ..., value: ...}形式。

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

答案 13 :(得分:3)

jsut 使用 vanilla js(ES6 版本)

// no need new Array constructor, just using an array literal
const arr1 = [{name: "lang", value: "English"}, {name: "age", value: "18"}];
const arr2 = [{name: "childs", value: '5'}, {name: "lang", value: "German"}];

// 1. create a map
const map = new Map();

// 2. concat array
// arr1.concat(arr2) === [...arr1, ...arr2]
const arr3 = [...arr1, ...arr2];

// 3. for ... of, iterator array
for(const obj of arr3) {
  if(!map.has(obj.name)) {
    // add
    map.set(obj.name, obj);
  } else {
    // update
    map.set(obj.name, {
      ...map.get(obj.name),
      ...obj,
    });
  }
}

// 4. get new merged unqiue array
const arr4 = [...map.values()];

console.log(`result array =`, JSON.stringify(arr4, null, 4));

/*

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

*/

测试 ✅ (Chrome)

enter image description here

参考

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...of

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Grammar_and_types#array_literals

答案 14 :(得分:2)

jQuery Merge怎么样?

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

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

答案 15 :(得分:2)

  

简单的解决方案

var tx = [{"id":1},{"id":2}];
var tx1 = [{"id":3},{"id":4}];


var txHistory = tx.concat(tx1)

console.log(txHistory); 
// output
 // [{"id":1},{"id":2},{"id":3},{"id":4}];

答案 16 :(得分:2)

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

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的顺序。

答案 17 :(得分:2)

我遇到了同样的问题并且基于guya answer我扩展了下划线库并且还添加了一些我需要的功能。这是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
        });

希望它有用! 此致!

答案 18 :(得分:1)

在这里,我首先根据arr1中存在的元素来过滤arr2。如果存在,则不要将其添加到结果数组中,否则请添加。然后将arr2附加到结果中。

arr1.filter(item => {
  if (!arr2.some(item1=>item.name==item1.name)) {
    return item
  }
}).concat(arr2)

答案 19 :(得分:1)

您可以使用以下功能

const merge = (a, b, key = "id") =>
  a.filter(elem => !b.find(subElem => subElem[key] === elem[key]))
   .concat(b);

然后尝试

merge(arr1, arr2, 'name');

答案 20 :(得分:1)

发布此消息是因为与以前的答案不同,此请求是通用的,没有外部库O(n)实际过滤出重复项并保持OP要求的顺序(通过将最后一个匹配的元素放置在首次出现的位置) ):

function unique(array, keyfunc) {
    return array.reduce((result, entry) => {
        const key = keyfunc(entry)
        if(key in result.seen) {
            result.array[result.seen[key]] = entry
        } else {
            result.seen[key] = result.array.length
            result.array.push(entry)
        }
        return result
    }, { array: [], seen: {}}).array
}

用法:

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 = unique([...arr1, ...arr2], x => x.name)
/* arr3 == [ 
    {name: "lang", value: "German"}, 
    {name: "age", value: "18"},
    {name: "childs", value: "5"}
]*/

答案 21 :(得分:0)

利用JS Map解决方案:

const merge = (arr1, arr2, prop) => {
    const resultMap = new Map([...arr1.map((item) => [item[prop], item])]);
    arr2.forEach((item) => {
        const mapItem = resultMap.get(item[prop]);
        if (mapItem) Object.assign(mapItem, item);
        else resultMap.set(item[prop], item);
    });
    return [...resultMap.values()];
};

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

console.log(merge(arr1, arr2, "name"));

哪个会产生:

merge() function outcome

答案 22 :(得分:0)

只需使用 helprjs

const arr1 = [{ id: 1, name: 'Jack'}, { id: 2, name: 'Jack'}];
const arr2 = [{ id: 2, name: 'Jane'}, { id: 3, name: 'Rod'}];

mergeArrays(arr1, arr2, "name");
// [{ id: 1, name: 'Jack'}, { id: 2, name: 'Jane'}, { id: 3, name: 'Rod'}];

mergeArrays(arr1, arr2, "id");
// [{ id: 1, name: 'Jack'}, { id: 2, name: 'Jack'}, { id: 3, name: 'Rod'}];

查看demo

答案 23 :(得分:0)

const arr1 = [{ name: "lang", value: "English" }, { name: "age", value: "18" }];
const arr2 = [{ name: "childs", value: '5' }, { name: "lang", value: "German" }];

const mergeArrOfObjects = (dataset1, dataset2) => {
    const map1 = new Map();
    dataset1.map((d1, i) => {
        map1.set(d1.name, i);
    })
    for (let d2 of dataset2) {
        if (d2 && map1.has(d2.name)) {
            dataset1[map1.get(d2.name)] = d2;
        } else if(d2){
            dataset1.push(d2);
        }
    }
    return dataset1;
};

const arr3 = mergeArrOfObjects(arr1, arr2);
console.log(arr3);

答案 24 :(得分:0)

基于@YOU的答案,但保留顺序:

%system1.m
function [dx] = system1(t,x,parameters)
dx = zeros(4,1);

a1 = parameters(1);
a2 = parameters(2);
a3 = parameters(3);
a4 = parameters(4);
b1 = parameters(5);
b2 = parameters(6);
b3 = parameters(7);
b4 = parameters(8);

dx(1) = x(2); %dtheta1 = angular velocity1
dx(2) = x(3); %d(angular velocity1) = angular acceleration1
dx(4) = x(5); %dtheta2 = angular velocity2
dx(5) = x(6); %d(angular velocity2) = angular acceleration2

dx(2) = a1*x(1)+a2*x(4)+a3*x(2)+a4*x(5); %motion equation 1
dx(5) = b1*x(1)+b2*x(4)+b3*x(2)+b4*x(5); %motion equation 2

%CA2Lou.m
%set parameters
clear;

a1 = -12;
a2 = 12;
a3 = 0;
a4 = 0;
b1 = 4;
b2 = -4;
b3 = 0;
b4 = 0;

parameters = [a1 a2 a3 a4 b1 b2 b3 b4];

%set final time
tf = .5;

options = odeset('MaxStep',.05);

%setting initial conditions
InitialConditions = [90 0 0 0 0 0];

[t_sol,x_sol] = ode45(@system1,[0 tf],InitialConditions,[],parameters);

我知道这个解决方案效率较低,但如果你想保留订单并仍然更新对象,这是必要的。

答案 25 :(得分:0)

var arr1 = [{ name: "lang", value: "English" }, { name: "age", value: "18" }];
var arr2 = [{ name: "childs", value: '5' }, { name: "lang", value: "German" }];

function mergeArrayByProperty(arr1, arr2, prop) {
    var newArray =
        arr1.map(item => {
            if (typeof (item[prop]) !== "undefined") {
                var nItems = arr2.filter(ni => { if (typeof (ni[prop]) !== "undefined" && ni[prop] === item[prop]) return ni; });
                if (nItems.length > 0) {
                    item = Object.assign({}, item, nItems[0]);
                }
                return item;
            }
        });
    var arr2nd = arr2.flatMap(item => { return item[prop] });
    var arr1nd = arr1.flatMap(item => { return item[prop] });
    var nonDupArr = arr2nd.map(p => { if (arr1nd.includes(p) === false) return arr2.filter(i2 => { if (i2[prop] === p) return Object.assign({}, i2) })[0]; });
    return newArray.concat(nonDupArr).filter(i=>{if(i !== null)return i})
}
var arr = mergeArrayByProperty(arr1, arr2, 'name');
console.log(arr)
我知道这已经得到了很多回答,但我想我会分享。

这会在第一个数组中找到重复的键并合并具有相同键值的第二个数组对象。如果在第二个数组中找不到值,则使用原始对象。如您所见,lang 在结果集中只出现一次;以德语为价值。

答案 26 :(得分:0)

您可以利用哈希映射和Object.values在大约O(3n)的时间内完成此操作。这看起来像O(n ^ 2),但外部循环只是迭代要合并的数组。

function uniqueMerge(arrays) {
  const results = {};
  arrays.forEach((arr) => {
    arr.forEach(item => {
      results[item.name] = item;
    });
  });

  return Object.values(results);
}

enter image description here

答案 27 :(得分:0)

let mergeArray = arrA.filter(aItem => !arrB.find(bItem => aItem.name === bItem.name))

答案 28 :(得分:0)

const array1 = [{id:1,name:'ganza'},
{id:2,name:'respice dddd'},{id:4,name:'respice dddd'},{id:6,name:'respice dddd'},
{id:7,name:'respice dddd'}];
const array2 = [{id:1,name:'ganza respice'},{id:2,name:'respice'},{id:3,name:'mg'}];

 function mergeTwoArray(array1,array2){

    return array1.map((item,i)=>{
        if(array2[i] && item.id===array2[i].id){
          return array2[i];
          }else{
            return item;
          }
    });
  }

const result = mergeTwoArray(array1,array2);
console.log(result);
//here is the result:  Array [Object { id: 1, name: "ganza respice" },
 Object { id: 2, name: "respice" }, Object { id: 4, name: "respice dddd" }, 
Object { id: 6, name: "respice dddd" }, Object { id: 7, name: "respice dddd" }]

答案 29 :(得分:0)

const array1 = [{id:1,name:'ganza'},
{id:2,name:'respice dddd'},{id:4,name:'respice dddd'},{id:6,name:'respice dddd'},
{id:7,name:'respice dddd'}];
const array2 = [{id:1,name:'ganza respice'},{id:2,name:'respice'},{id:3,name:'mg'}];

 function mergeTwoArray(array1,array2){

    return array1.map((item,i)=>{
        if(array2[i] && item.id===array2[i].id){
          return array2[i];
          }else{
            return item;
          }
    });
  }

const result = merge(array1,array2);
console.log(result);
//here is the result:  Array [Object { id: 1, name: "ganza respice" }, Object { id: 2, name: "respice" }, Object { id: 4, name: "respice dddd" }, Object { id: 6, name: "respice dddd" }, Object { id: 7, name: "respice dddd" }]

答案 30 :(得分:0)

使用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

答案 31 :(得分:0)

const arr1 = ["Vijendra","Singh"];
const arr2 = ["Singh", "Shakya"];

arr2.forEach(item => {
        if(!arr1.find(k => k===item))
          arr1.push(item)
    });


console.log(arr1)

答案 32 :(得分:0)

尝试一下:

var a = [{"a":20, "b":10,"c":"c","d":"asd","f":"any"}]
var b = [{"a":20, "b":10,"c":"c", "e":"nan","g":10200}]

var p = []
_.map(a, function(da){
var chk = _.filter(b, function(ds){
return da.a ===ds.a
})[0]
p.push(_.extend(da, chk))


})

console.log(p)

输出将为:

  [{
    "a": 20,
    "b": 10,
    "c": "c",
    "d": "asd",
    "f": "any",
    "e": "nan",
    "g": 10200
  }]

答案 33 :(得分:0)

如果要合并2个数组,但要删除重复的对象,请使用此方法。 在每个对象的.uniqueId上标识出重复项

function mergeObjectArraysRemovingDuplicates(firstObjectArray, secondObjectArray) {
  return firstObjectArray.concat(
    secondObjectArray.filter((object) => !firstObjectArray.map((x) => x.uniqueId).includes(object.uniqueId)),
  );
}

答案 34 :(得分:0)

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

答案 35 :(得分:0)

merge(a, b, key) {
    let merged = [];
    a.forEach(aitem => {
        let found = b.find( bitem => aitem[key] === bitem[key]);
        merged.push(found? found: aitem);
    });
    return merged;
}

答案 36 :(得分:0)

离开我的头顶 - 尝试jquery extend

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

答案 37 :(得分:0)

const extend = function*(ls,xs){
   yield* ls;
   yield* xs;
}

console.log( [...extend([1,2,3],[4,5,6])]  );

答案 38 :(得分:0)

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

&#13;
&#13;
(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));
&#13;
.as-console-wrapper { top: 0; max-height: 100% !important; }
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
&#13;
&#13;
&#13;

ES6版本

(function($) {
  $.extendObjectArray = (destArr, srcArr, key) => {
    srcArr.forEach(srcObj => (existObj => {
      if (existObj.length) {
        $.extend(true, destArr[destArr.indexOf(existObj[0])], srcObj);
      } else {
        destArr.push(srcObj);
      }
    })(destArr.filter(v => v[key] === srcObj[key])));
    return destArr;
  };
})(jQuery);

答案 39 :(得分:-1)

//No need for using libraries and so on..
//You can just do
var arr1 = [{name: "lang", value: "English"},{name: "age", value: "18"}];
var arr2 = [{name : "childs", value: '5'}, {name: "lang", value: "German"}];

const arr3 = arr1.concat(arr2);
console.log(arr3);  // final merged result will be in arr3