JavaScript - Return differences between two Objects?
You can use Object.keys() and Array.includes() to do that.
var data = {
"48": "{\"sid\":\"48\",\"name\":\"title 1\"}",
"77": "{\"sid\":\"77\",\"name\":\"The blahblah title\"}",
"83": "{\"sid\":\"83\",\"name\":\"The blahblah derp\"}",
"87": "{\"sid\":\"87\",\"name\":\"The derpy title 4\"}"
};
var obj1 = {
"48": "{\"sid\":\"48\",\"name\":\"title 1\"}",
"77": "{\"sid\":\"77\",\"name\":\"The blahblah title\"}"
};
var result = {};
var keys = Object.keys(obj1);
for (var key in data) {
if (!keys.includes(key)) {
result[key] = data[key];
}
}
console.log(result);
An object oriented approach using reduce
.
const obj1 = {
'48': '{"sid":"48","name":"title 1"}',
'77': '{"sid":"77","name":"The blahblah title"}',
}
const obj2 = {
'48': '{"sid":"48","name":"title 1"}',
'77': '{"sid":"77","name":"The blahblah title"}',
'83': '{"sid":"83","name":"The blahblah derp"}',
'87': '{"sid":"87","name":"The derpy title 4"}',
}
const combinedObject = { ...obj1, ...obj2 }
const diff = Object.entries(combinedObject).reduce((acc, [key, value]) => {
if (
!Object.values(obj1).includes(value) ||
!Object.values(obj2).includes(value)
)
acc[key] = value
return acc
}, {})
console.log(diff)
This approach will work with several objects and does not treat one object as the primary one for comparison.