I have 2 objects.
The one object is Original Data.
const origin = { name: 'John', id: 'Doe', item: { drink: 'coffee', money: 0 } }
And the other object is Copied and Edited Data
const copied = { name: 'Alex', id: 'Doe', item: { drink: 'water', money: 0 } }
I would like to compare them and get diff only.
const out = compareObj(origin, copied);
console.log(out)
/*
{ name: 'Alex', item: { drink: 'water' } }
*/
How can I get this?
Thanks in advance.
You can recursively loop over the object and delete the non-duplicate properties from the copy object.
And if a property exists on the the original object and not on the copy, then add it into the copy object. Following part of the code does that:
if (!copy.hasOwnProperty(k)) {
copy[k] = v;
}
function compare(original, copy) {
for (let [k, v] of Object.entries(original)) {
if (typeof v === "object" && v !== null) {
if (!copy.hasOwnProperty(k)) {
copy[k] = v;
} else {
compare(v, copy?.[k]);
}
} else {
if (Object.is(v, copy?.[k])) {
delete copy?.[k];
}
}
}
return copy;
}
const
original = { name: "John", id: "Doe", item: { drink: "coffee", money: 0, honey: 24 } },
copy = { name: "Alex", id: "Doe", item: { drink: "water", money: 0 } },
diff = compare(original, JSON.parse(JSON.stringify(copy)));
console.log(diff);
Note: You need to pass a clone of the copy object to the function since it mutates the passed copy object.