Lets say I have two different objects
let obj1 = {
"value1" : "1",
"value2" : "2",
"value3" : "3",
"value4" : "4"
}
let obj2 = {
"value1" : "1",
"value2" : "3",
"value3" : "3",
"value4" : "5"
}
I need a the differences in a new object that will depend on obj2
result = { "value2":"3" , "value4" : "5" }
The case can be too , that obj1 === undefined
In that case, I need all the values from obj2
Currently I have
let result = {}
let singleChange = false
for (const i of Object.entries(obj2)) {
if (obj1 && obj1[i[0]] !== i[1]) {
result [i[0]] = i[1];
singleChange = true
} else if(!singleChange) {
result = obj2;
}
}
But it doesnt really sem to work properly all the times. Is there a better way to write this?
A modern version with entries and fromEntries:
let obj1 = {
"value1" : "1",
"value2" : "2",
"value3" : "3",
"value4" : "4"
}
let obj2 = {
"value1" : "1",
"value2" : "3",
"value3" : "3",
"value4" : "5"
}
let obj3 = undefined;
function objIntersection(o1, o2) {
const filteredArray = Object.entries(o2)
.filter(([k,v]) => o1?.[k] !== v);
return Object.fromEntries(filteredArray);
}
console.log(objIntersection(obj1, obj2));
console.log(objIntersection(obj3, obj2));
const obj1 = {
value1: '1',
value2: '2',
value3: '3',
value4: '4',
};
const obj2 = {
value1: '1',
value2: '3',
value3: '3',
value4: '5',
};
// find only the values that are different
const diff = (obj1, obj2) => {
const obj3 = {};
for (const key in obj1) {
if (obj1[key] !== obj2[key]) {
obj3[key] = obj2[key];
}
}
return obj3;
}
console.log(diff(obj1, obj2));
You could get the entries of the second object and filter with the first one.
const
getDifference = (a, b) => Object.fromEntries(Object
.entries(b)
.filter(([k, v]) => a[k] !== v)
),
obj1 = { value1 : "1", value2 : "2", value3 : "3", value4 : "4" },
obj2 = { value1 : "1", value2 : "3", value3 : "3", value4 : "5" },
result = getDifference(obj1, obj2);
console.log(result);