比较前后两个数组对象的差异
代码语言:javascript复制js比较前后两个数组对象的差异,比如是添加了什么数据或者删除了什么数据。
// 两个数组对象中有相同的键如 id
// 其中, oldData为初始数据, newData为当前数据
const getChangeData = (oldData, newData) => {
let delData = oldData.filter(
(item2) => !newData.some((item1) => item2?.id === item1?.id)
);
let addData = newData.filter(
(item2) => !oldData.some((item1) => item2?.id === item1?.id)
);
let changeData = {
delData,
addData,
};
return changeData;
let data01 = [
{
id: 1,
type: "直尺",
price: 2,
},
{
id: 2,
type: "直尺",
price: 3,
},
{
id: 3,
type: "直尺",
price: 4,
},
{
id: 4,
type: "直尺",
price: 5,
},
];
let data02 = [
{
id: 2,
type: "直尺",
price: 3,
},
{
id: 5,
type: "文具盒",
price: 10,
},
{
id: 6,
type: "铅笔",
price: 2,
},
];
}
const a = getChangeData(data01, data02);
console.log(a);
输出: { delData: [ { id: 1, type: ‘直尺’, price: 2 }, { id: 3, type: ‘直尺’, price: 4 }, { id: 4, type: ‘直尺’, price: 5 } ], addData: [ { id: 5, type: ‘文具盒’, price: 10 }, { id: 6, type: ‘铅笔’, price: 2 } ] }