Let’s say I have two objects of arrays:
const newObj = {
description: "abcd",
type: "anything",
list: [
{ id: 1, name: "Peter" },
{ id: 2, name: "Cathenna" },
{ id: 3, name: "Chiyo" }
]
}
const oldObj = {
description: "wwew",
type: "anything",
list: [
{ id: 1, name: "Amara" },
{ id: 2, name: "shinzo" },
{ id: 3, name: "Chiyo" }
]
}
I want to find all the updated data in newObj objects. Ex, description of oldObj is updated to “abcd” in newObj and in list name of two objects has been updated. So, my expected output is:
const extractObjDiff = {
description: "abcd",
list: [
{ id: 1, name: "Peter" },
{ id: 2, name: "Cathenna" }
]
}
I have tried below code but it’s not working for array list.
function extractObjDiff(newObj, oldObj) {
var r = {};
for (var prop in newObj) {
if (!oldObj.hasOwnProperty(prop)) {
if (Array.isArray(newObj)) {
r = newObj;
} else {
r[prop] = newObj[prop];
}
} else if (newObj[prop] === Object(newObj[prop])) {
var difference = newObj[prop].length !== oldObj[prop].length ? newObj[prop] : extractObjDiff(newObj[prop], oldObj[prop], []);
if (Object.keys(difference).length > 0) r[prop] = difference;
} else if (newObj[prop] !== oldObj[prop]) {
if (newObj[prop] === undefined)
r[prop] = 'undefined';
if (newObj[prop] === null)
r[prop] = null;
else if (typeof newObj[prop] === 'function')
r[prop] = 'function';
else if (typeof newObj[prop] === 'object')
r[prop] = 'object'
else if (Array.isArray(newObj))
r = newObj;
else
r[prop] = newObj[prop];
}
}
return r;
}