Is there an ES6 function that will return an object containing property changes?
Doesn't have to be ES6, but you can implement it like this:
var object = {name: 'Fred', age: 20, weight: 100};
var object2 = {name: 'Fred', age: 21, weight: 120, height: 70};
function getChangesFromObjectTwo(source, target) {
return Object.fromEntries(Object.entries({...source, ...target})
.filter(([key, value]) => !Object.is(source[key], value)));
}
// returns {age:21, weight: 120};
var changes = getChangesFromObjectTwo(object, object2);
console.log(changes);
Added properties also included
P.S. Using Object.is to bypass NaN problem
Assuming that keys are identical in both objects o1
and o2
, you can just use Object.keys()
with a a reduce()
operation:
Object.keys(o2).reduce((a, k) => (o1[k] !== o2[k] && (a[k] = o2[k]), a), {});
Full snippet:
const object1 = {name:'Fred', age: 20, weight: 100};
const object2 = {name:'Fred', age: 21, weight: 120};
function getChanges(o1, o2) {
return Object.keys(o2)
.reduce((a, k) => (o1[k] !== o2[k] && (a[k] = o2[k]), a), {});
}
console.log(getChanges(object1, object2));
Or if you're working in an environment that supports Object.entries()
, you can avoid a couple of lookups:
Object.entries(o2).reduce((a, [k, v]) => (o1[k] !== v && (a[k] = v), a), {});
Full snippet:
const object1 = {name:'Fred', age: 20, weight: 100};
const object2 = {name:'Fred', age: 21, weight: 120};
function getChanges(o1, o2) {
return Object.entries(o2)
.reduce((a, [k, v]) => (o1[k] !== v && (a[k] = v), a), {});
}
console.log(getChanges(object1, object2));
Object.assign
does the opposite of what you want: it modifies an object based on an object listing changes.
There's no built-in function that does it, but you can easily implement your own.
For a single level depth observation, it should be enough to:
function getChangesFromObjectTwo(obj1, obj2){
//Using Set to create an unique list
return [...new Set([
...Reflect.ownKeys(obj1),
...Reflect.ownKeys(obj2)
])]
.map(k => [k, obj1[k], obj2[k]])
.filter(([, v1, v2]) => v1 !== v2)
.reduce((acc, [k, , v]) => (
acc[k] = v,
acc
), {})
}
var object = {name:"Fred", age:20, weight: 100};
var object2 = {name:"Fred", age:21, weight: 120, height: 70};
console.log(getChangesFromObjectTwo(object, object2));