通过一个相同的字段在合并两个数组
var player = [{score: 1, name: 'Jeff'},{score: 2, name: 'Jeff',age:18}]; var player1 = [{score: 1, name: 'aaa',age:16}];
根据 score:1 这条件进行合并 如下
[{score: 1, name: 'aaa',age:16},{score: 2, name: 'Jeff',age:18}];
代码实现:
var newPlayer = player.concat([]); for ( var i = 0; i <newPlayer.length; i++){ for ( var j = 0; j <player1.length; j++){ if(newPlayer[i].score==player1[j].score){ //对象合并 newPlayer[i] = Object.assign({}, newPlayer[i], player1[j]) } } } console.log(player); console.log(newPlayer);
这里有一个小坑,注意一下
不能使用 var newarr= arr;不然修改新数组时也会修改旧数组 concat() 方法用于连接两个或多个数组
或者如果你使用对象扩展语法,可以写成:
var newPlayer = {...player, score: 2};