Reputation: 10964
I have two JS objects which contain some arrays. I'd like to compare the two objects and create a third object, containing arrays only unique to secondObj
.
They look like this:
firstObj : {
Jim_Array : [...],
Joe_Array : [...],
Bill_Array : [...]
}
secondObj : {
Bill_Array : [...],
Sam_Array : [...],
Kate_Array : [...],
Jim_Array : [...],
Joe_Array : [...]
}
I'd like to compare the two objects and end up with the following:
thirdObj : {
Sam_Array : [...],
Kate_Array : [...]
}
Upvotes: 1
Views: 147
Reputation: 27976
A solution using underscore:
var result = _.pick(secondObj, _.difference( _.keys(secondObj), _.keys(firstObj)));
Upvotes: 1
Reputation: 122037
You can use Object.keys()
with reduce()
and check if firstObj has property of secondObj with hasOwnProperty()
, if not add to new object.
var firstObj = {Jim_Array : ['...'], Joe_Array : ['...'], Bill_Array : ['...']}
var secondObj = {Bill_Array : ['...'], Sam_Array : ['...'], Kate_Array : ['...'], Jim_Array : ['...'], Joe_Array : ['...']}
var result = Object.keys(secondObj).reduce(function(o, e) {
if(!firstObj.hasOwnProperty(e)) o[e] = secondObj[e];
return o;
}, {});
console.log(result)
Upvotes: 2
Reputation: 28455
You can try something like following
var thirdObj = {};
for (var key in secondObj) {
if(!firstObj.hasOwnProperty(key)) {
// In case you need to compare the array additional check will come here
thirdObj[key] = secondObj[key];
}
}
Another way
var thirdObj = {};
for (var key in secondObj) {
if(firstObj[key] === undefined) {
// In case you need to compare the array additional check will come here
thirdObj[key] = secondObj[key];
}
}
Upvotes: 2