需求:
把oldData
里与newData
相同的项替换成newData
所对应的,如果newData
里没有跟oldData
相同的项就不替换
var oldData = [ { name:"b",state:"no" }, { name:"d",state:"no" }, { name:"e",state:"no" }, { name:"f",state:"no" }]var newData = [ { name:"a",state:"yes" }, { name:"b",state:"yes" }, { name:"f",state:"yes" }]复制代码
解决方案:
var result = []result = oldData.map((item,index)=>{ let update = newData.find((el,i)=>{ return el.name===item.name}); return update?update:item})console.log(result)// 合并后的结果要求如下// [// { name:"b",state:"yes" },// { name:"d",state:"no" },// { name:"e",state:"no" },// { name:"f",state:"yes" }// ]复制代码