I have two JavaScript arrays orig
(the original array of objects) and update
(the updated orig array of objects) that have the same length and contain objects, and I want to output the differences between the each pair of objects.
Example:
var orig = [{enabled:"true", name:"Obj1", id:3},{enabled:"true", name:"Obj2", id:4}];
var update = [{enabled:"true", name:"Obj1", id:3}, {enabled:"true", name:"Obj2-updated", id:4}];
The output should be: name:"Obj2-updated"
I implemented something but it needs optimization...
for(var prop=0; prop<orig.length; prop++) {
for(prop=0; prop<update.length; prop++) {
if(orig[prop].enabled != update.enabled) { console.log(update.enabled) }
if(orig[prop].name != update[prop].name) { console.log(update[prop].name) }
if(orig[prop].id != update[prop].id) { console.log(update[prop].id) }
}
}
You could filter the keys and get a result set with the updated keys.
You could use a library like lodash or Ramda to do it in a concise manner. In the case of Ramda you could do:
R.difference(update, orig);
Use
Object.keys
to cycle through your object. Something like:Assuming, that the property names of both are identical and the values are just primitives (no objects, arrays etc.):
You can use a single loop to go through the properties of the original object and check against the updated object to find out which properties have been modified.