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

我需要合并这两个数组的对象,并创建以下数组:

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

是否有任何 JavaScript 或 jQuery 函数可以做到这一点?

$.extend不适合我,它回来了

var arr4 = new Array({name : "childs", value: '5'},
{name: "lang", value: "German"});
457594 次浏览

首先,试试 Jquery 扩展

var arr3 = jQuery.extend(arr1,arr2....)
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

那 jQuery Merge 呢?

Http://api.jquery.com/jquery.merge/

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

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

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

给你相同的东西,在 aarr3与“德国”替换为“煎饼”。

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

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

合并两个数组:

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

2019年10月12日最新情况

新版本只基于新的 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)

这个答案已经过时了,现在已经不再需要 loash 和 underscore 这样的即兴表演了。 在这个新版本中,我们正在使用的是 目标(一)数组,并且希望保持最新。 来源(arr2)数组是新数据的来源,我们希望将其合并到 目标数组中。

我们在 来源数组中循环查找新数据,对于在 目标数组中尚未找到的每个对象,我们只需使用 < strong > target.push (source Element)添加该对象 如果,基于我们的 Key 属性(“ name”),一个对象已经在我们的目标数组-我们更新其属性和值使用 分配(targetElement,source Element)。 我们的“目标”将始终是相同的数组和更新的内容。


旧的答案使用下划线或 loash

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

演示: http://jsfiddle.net/guya/eAWKR/

下面是一个更通用的函数,它将使用对象的属性合并两个数组。在这种情况下,属性是“ name”

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);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.core.min.js"></script>

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

我也面临着同样的问题,基于 盖亚回答,我扩展了下划线库,并添加了一些我需要的功能。这是 要点

/**
* 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
});

希望有用! 问候!

还有一种使用 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"/>

Var newArray = yourArray.concat (other Array) ; Log (‘ Concatenated newArray:’,newArray) ;

如果你想在 JavaScript 中合并两个对象数组,你可以使用这个单行技巧

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

我最近被这个问题难住了,我来到这里希望有一个答案,但公认的答案使用2 for 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的顺序。

带着乐呵呵的语气:

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

基于@You 的回答,但保持顺序:

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

我知道这个解决方案效率较低,但是如果您想保持顺序并仍然更新对象,那么这是必要的。

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

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




// for posterity, here's the old skool version


function merge(a, b, prop) {
var reduced = [];
for (var i = 0; i < a.length; i++) {
var aitem = a[i];
var found = false;
for (var ii = 0; ii < b.length; ii++) {
if (aitem[prop] === b[ii][prop]) {
found = true;
break;
}
}
if (!found) {
reduced.push(aitem);
}
}
return reduced.concat(b);
}

下面是我编写的一个 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>


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

使用您想要的 loash _. uniqBy

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


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

一号,二号的命令很重要!

参见文件 https://lodash.com/docs/4.17.4#uniqBy

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

以下是我在 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'));

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

arr1.filter(item => {
if (!arr2.some(item1=>item.name==item1.name)) {
return item
}
}).concat(arr2)
const extend = function*(ls,xs){
yield* ls;
yield* xs;
}


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

使用 ES6扩展运算符非常简单:

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>

Merged Array: [ {a: 'HI!'}, {b: 'HOW'} {c: 'ARE'}, {d: 'YOU?'} ]

注意: 上面的解决方案是使用 ES6扩展运算符合并两个数组。

2020年1月7日@bh4r4th 编辑: 因为上下文在我最初的解决方案之后由于编辑而改变。我想更新我的解决方案,以符合当前的标准。也就是说,

  1. 在不创建重复对象的情况下合并数组对象,

  2. 如果先前数组中已经存在 name属性,则更新 value

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


// Convert to key value dictionary or object
const convertToKeyValueDict = arrayObj => {
const val = {}
arrayObj.forEach(ob => {
val[ob.name] = ob.value
})
return val
}


// update or merge array
const updateOrMerge = (a1, a2) => {
const ob1 = convertToKeyValueDict(a1)
const ob2 = convertToKeyValueDict(a2)
// Note: Spread operator with objects used here
const merged_obj = {...ob1, ...ob2}
const val = Object.entries(merged_obj)
return val.map(obj => ({ name: obj[0], value: obj[1] }))
}


const v1 = updateOrMerge(arr1, arr2)
const v2 = updateOrMerge(v1, arr3)
console.log(`Merged array1 and array2: ${JSON.stringify(v1)} \n\n`)
console.log(`Merged above response and array3: ${JSON.stringify(v2)} \n\n`)
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

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

你可以使用以下函数

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

试试看

merge(arr1, arr2, 'name');

简单的解决办法

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

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

如果你想合并2个数组,但删除重复的对象使用这个。 在每个对象的 .uniqueId上标识重复

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

试试这个:

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
}]
const arr1 = ["Vijendra","Singh"];
const arr2 = ["Singh", "Shakya"];


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




console.log(arr1)

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

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


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

您可以利用散列映射和 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

发表这篇文章是因为与前面的答案不同,这个答案是通用的,没有外部库 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"}
]*/

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 在结果集中只能找到一次; 该值使用德语表示。

我会合并两个数组的副本,然后使用我的 这个答案删除副本。这看起来像最短的方法。

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)

//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

只是使用香草 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"
}
]


*/

测试 something (铬)

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

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

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

看看 小样

基于这个问题,我理解有一个 key,您希望使用它来覆盖其他属性,而不是合并它们。

interface Foo {
name: string;
value: string;
}


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


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

我们可以使用 MapReduce的组合来选择将用于覆盖记录的 key

const merged: Foo[] = Array.from(
[...arr1, ...arr2].reduce(
(acc, curr) => acc.set(curr.name, curr),
new Map<Foo["name"], Foo>(),
)
.values(),
);


// [
//   { name: "lang", value: "German" },
//   { name: "age", value: "18" },
//   { name: "childs", value: "5" },
// ];

得票最高的回复不符合要求,@Diogo Alves 和@Pietro 的回答是正确的,但你需要小心订单。

enter image description here

enter image description here

如果你想在 JavaScript 中合并两个对象数组,你可以这样使用 为了... 为了..:

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


for (const x of arr2){ arr1.push(x); }


console.log(arr1);
  1. 使用传统的 for循环

const merge = (first, second) => {
for(let i=0; i<second.length; i++) {
first.push(second[i]);
}
return first;
}


console.log(merge([1,2,3], [4,5,6])); // [1,2,3,4,5,6]
console.log(merge(merge([1,2,3], [4,5,6]), [7,8,9])); // [1,2,3,4,5,6,7,8,9]

  1. 使用 Spread操作符

const arr1 = [1,2,3];
const arr2 = [4,5,6];


// Merge arrays
const merged = [...arr1, ...arr2];


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

  1. 使用 concat()数组方法

const arr1 = [1,2,3];
const arr2 = [4,5,6];


// Merge arrays
const merged1 = arr1.concat(arr2); // bit confusing, seems like `arr1` itself is being modified but it's not
const merged2 = [].concat(arr1, arr2); // cleaner approach


console.log(merged1); // [1,2,3,4,5,6]
console.log(merged2); // [1,2,3,4,5,6]

  1. 使用 push()数组方法

const arr1A = [1,2,3];
const arr2A = [4,5,6];


const arr1B = [1,2,3];
const arr2B = [4,5,6];


const arr1C = [1,2,3];
const arr2C = [4,5,6];
const arr3C = [7,8,9];


// Merge arrays
const merged1 = arr1A.push(...arr2A);


// Merging without the ... on arr2B
const merged2 = arr1B.push(arr2B);


// Merge more than two arrays
arr1C.push(...[...arr2C, ...arr3C]);
console.log(arr1C); // [1,2,3,4,5,6,7,8,9]


console.log(merged1); // 6
console.log(arr1A); // [1,2,3,4,5,6]
console.log(arr2A); // [4,5,6]


console.log(merged2); // 4
console.log(arr1B); // [1,2,3,[4,5,6]]
console.log(arr2B); // [4,5,6]

  1. 使用 reduce()数组方法

const arr1 = [1,2,3];
const arr2 = [4,5,6];


const merged = arr2.reduce((arr, item) => {
arr.push(item);
return arr;
}, arr1);


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

总结一下,

  • 在 JavaScript 中,有多种方法可以将两个或多个数组合并为一个数组。
  • 使用 spread算子或 concat()方法是最优解。
  • 如果确定要合并的所有输入都是数组,请使用扩展运算符。如果您不确定,请使用 concat()方法。
  • 当您想要更改其中一个输入数组以进行合并时,可以使用 push()方法来合并数组。
  • 使用 reduce()方法合并数组有一点开销。

更多信息请参考详细的博客 给你和视频 给你