I have an object where at global level I have the changed values and inside one property called initialData
I have the initial value, so what I am trying to do is, based on the array mentioned values I need to find whether the initialData
has been changed or not.
const eligibleFields = ['address_line_1', "is_new"]
const object = {
"id": "1",
"isGetting": false,
"address_line_1": "Washington DC",
"address_line_2": "Newyork",
"isOpen": false,
"comment": "Changed Data",
"initialData": {
"id": 1,
"is_new": true,
"address": {
"address_line_1": "Washington",
"address_line_2": "Newyork",
},
"comment": "Initial Data"
}
}
Here first I need to loop through the mentioned fields like address_line_1
and take the value as Washington
, now compare it outer not inside initialData, so outer its Washington DC
, so there is a change.
Now I need to return a boolean value.
This is working, but is there a simple way?
const eligibleFields = ['address_line_2', "is_new"]
const object = {
"id": "1",
"isGetting": false,
"address_line_1": "Washington DC",
"address_line_2": "Newyork",
"isOpen": false,
"comment": "Changed Data",
"initialData": {
"id": 1,
"is_new": true,
"address": {
"address_line_1": "Washington",
"address_line_2": "Newyork",
},
"comment": "Initial Data"
}
}
function findVal(obj, key) {
var seen = new Set,
active = [obj];
while (active.length) {
var new_active = [],
found = [];
for (var i = 0; i < active.length; i++) {
Object.keys(active[i]).forEach(function(k) {
var x = active[i][k];
if (k === key) {
found.push(x);
} else if (x && typeof x === "object" &&
!seen.has(x)) {
seen.add(x);
new_active.push(x);
}
});
}
if (found.length) return found;
active = new_active;
}
return null;
}
let isChanged = eligibleFields.some(field => {
let initialValue = findVal(object.initialData, field)?.[0]
if (initialValue) {
let changedValue = findVal(object, field)?.[0]
if (changedValue != initialValue) {
console.log("changedValue =>",changedValue, ",", "initialValue =>",initialValue)
return true
}
}
})
console.log(isChanged)