Requirement: Compare the difference between two objects and return the difference object.
This function I made will find new or changed values, and new elements of the array.
function isObject(object) {
return object !== null && typeof object === 'object' && !Array.isArray(object);
}
function compareObject(data, lastData, diff = {}) {
const keys = Object.keys(data);
for (let key of keys) {
if (lastData === undefined) {
lastData = {};
}
if (lastData[key] === undefined) {
diff[key] = JSON.parse(JSON.stringify(data[key]));
continue
};
if (Array.isArray(data[key])) {
if (data[key].length !== lastData[key].length) {
const diffArr = data[key].filter((item, index) => lastData[key][index] === undefined)
diff[key] = diffArr;
continue
}
};
if (!isObject(data[key]) && JSON.stringify(data[key]) !== JSON.stringify(lastData[key])) {
diff[key] = data[key];
continue
}
if (isObject(data[key])) {
if (Object.keys(compareObject(data[key], lastData[key])).length !== 0) {
diff[key] = compareObject(data[key], lastData[key]);
continue
}
};
}
return diff
}
origin example as below:
const oldData = {
account_info: {
age: 30,
favor: ["coding", "music"],
cars: [{ brand: 'toyota', count: 1 }],
room: {
A01: "test1",
}
},
server: {
os: "Linux",
cloud: "gcp"
}
}
const newData = {
account_info: {
age: 30,
favor: ["coding", "music", "see movie"],
cars: [{ brand: 'toyota', count: 2 }, { brand: 'KIA', count: 1 }],
room: {
A01: "test2",
A02: "black",
A03: "white"
}
},
"server": {
"os": "Linux",
}
}
// result(without first object value changed in array)
// {
// account_info: {
// favor: [ 'see movie' ],
// cars: [ { brand: 'KIA', count: 1 } ],
// room: { A01: 'test2', A02: 'black', A03: 'white' }
// }
// }
But new demand is also find out which object in the array has changed only value??
How can I extend this function?
Thanks!!