let arr1 = [
{'id':1,'name':'高','age':10},
{'id':2,'name':'张','age':20},
{'id':3,'name':'李','age':30},
{'id':4,'name':'赵‘,'age':10},
{'id':5,'name':'王’,'age':20},
];
let arr2 = [
{"id":1,"value":"111"},
{"id":2,"value":"11111"},
{"id":3,"value":"25462"},
{"id":4,"value":"23131"},
{"id":5,"value":"2315432"},
];
arr3 = [
{"id":1,"name":"高","value":"111"},
{"id":2,"name":"张","value":"11111"},
{"id":3,"name":"李","value":"25462"},
{"id":4,"name":"赵","value":"23131"},
{"id":5,"name":"王","value":"2315432"},
];
//对于数组arr1 和数组 arr2. 我们需要把数组arr1 里面的name属性以及值,根据id放在数组arr2 里面.也就数组arr3的形式
// 方法一arr2.map((item2) => {arr1.map((item1) => {if (item2.id == item1.id) {let json = {'name': item1.name};Object.assign(item2, json);return item2;}})})console.log(arr2);// 方法二const combined = arr2.reduce((acc, cur) => {const target = acc.find(e => e.id === cur.id);console.log(target)if (target) {Object.assign(target, cur);} else {acc.push(cur);}return acc;}, arr1);console.log('新数组2', combined);// 方法三for (let i = 0; i < arr2.length; i++) {for (let j = 0; j < arr1.length; j++) {if (arr2[i].id == arr1[j].id) {arr2[i].name = arr1[j].name;}}}console.log(arr2);
如果觉得《前端两个数组根据相同字段合并数组》对你有帮助,请点赞、收藏,并留下你的观点哦!