想以旧数据为基准,不改变旧数据里的某些元素,拿到新数据里没有的元素,再删除旧数据里多余的元素
//新
let a = [{"id":"1", "name":"用户1"},{"id":"2","name":"用户2"},{"id":"3","name":"用户3"},{"id":"4","name":"用户4"},{"id":"5","name":"用户5"}];
//旧
let b = [{"id":"2","name":"用户2",over:"例外"},{"id":"3","name":"用户3",over:"例外"},{"id":"4","name":"用户4",over:"例外"},{"id":"6","name":"用户6",over:"例外"}];
/*
已旧数据为基准
从新数据里 获取旧数据没有的数据
*/
a.forEach(t1 => {
if(b.findIndex(t2 => t1.id === t2.id) == -1){
b.push(t1);
}
});
/*
再从旧数据里 删除新数据没有的数据
*/
b.forEach((t1,index) => {
if(a.findIndex(t2 => t1.id === t2.id) == -1){
b.splice(index,1);
}
})
console.log(b);
/*
得到我们想要的数据
0: {id: "2", name: "用户2", over: "例外"}
1: {id: "3", name: "用户3", over: "例外"}
2: {id: "4", name: "用户4", over: "例外"}
3: {id: "1", name: "用户1"}
4: {id: "5", name: "用户5"}
*/