Let's say I have two versions:
let oldObj = {
name: "john",
location: "usa",
age: 43
}
let newObj = {
name: "john",
location: "usa",
age: 44
}
In the case age
changed.
Let's say I have two versions:
let oldObj = {
name: "john",
location: "usa",
age: 43
}
let newObj = {
name: "john",
location: "usa",
age: 44
}
In the case age
changed.
Assuming you want to only track changes (of primitive values) and not additions/deletions, you can just iterate over the values from one object and do direct comparisons with corresponding values in the other object:
let oldObj = {
name: "john",
location: "usa",
age: 43
}
let newObj = {
name: "john",
location: "usa",
age: 44
}
let changes = Object
.entries(oldObj)
.filter(([key, value]) => value !== newObj[key])
console.log(changes)
If you don't care about the values, you can just filter the keys instead:
let oldObj = {
name: "john",
location: "usa",
age: 43
}
let newObj = {
name: "john",
location: "usa",
age: 44
}
let changes = Object
.keys(oldObj)
.filter(key => oldObj[key] !== newObj[key])
console.log(changes)
If you want to include additions/deletions, you can first determine the object with the larger amount of keys and do similarly to above:
let oldObj = {
name: "john",
location: "usa",
age: 43
}
let newObj = {
name: "john",
location: "usa",
age: 44,
addition: 'test'
}
let [larger, smaller] = Object.keys(oldObj).length > Object.keys(newObj).length
? [oldObj, newObj]
: [newObj, oldObj]
let changes = Object
.entries(larger)
.filter(([key, value]) => !smaller.hasOwnProperty(key) || value !== smaller[key])
console.log(changes)
first thing you should do is to edit your question, and replace new
with something else, because new is a keyword in javascript used with constructor functions to create an instance of that particular constructor function.
let old = {
name: "john",
location: "usa",
age: 43
}
let _new = {
name: "john",
location: "usa",
age: 44
}
for ( let j in old ) {
if ( old[j] !== _new[j] ) {
console.log(`${old[j]} is not ${_new[j]}`);
}
}
the below code loops through the old
object, the content of j will be the keys of the old object, the if statement uses old[j]
to get the content of the j
key ( same thing applies to _new[j]
), the if statement also checks if the content and the type of _new[j]
and _old[j]
is the same. If you don't care about the types , you should remove one of the equal signs in the if statement