数组合并用于组合另一个数组中的键值,而不使用javascript重复相同的对象

时间:2018-03-05 09:58:15

标签: javascript

我尝试合并数组

var x =[{n:'s1', a:'sang', m1: 10}, {n:'s2', a:'sang', m1: 20}]

var y =[{n:'s1', a:'sang', m2: 20}, {n:'s2', a:'sang', m2: 20}]

after merging var a and var b I need result in var c like,

c = [{n:'s1', a:'sang', m1: 10, m2: 20},{{n:'s2', a:'sang', m1: 20,m2: 20}]

1 个答案:

答案 0 :(得分:1)

您可以使用Object(assign)方法:

var x =[{n:'s1', a:'sang', m1: 10}, {n:'s2', a:'sang', m1: 20}]

var y =[{n:'s1', a:'sang', m2: 20}, {n:'s2', a:'sang', m2: 20}]

var c = [];

x.forEach(a => {
	c.push( Object.assign({}, a, y.find( b => b.n === a.n) ) );
});

console.log( c );