Reputation: 7517
What is the easiest way to find the common members in two Javascript objects? This question is not about equality. I don't care about the values of each member, just that they exist in both objects.
Here's what I've done so far (using underscore.js):
_.intersection(_.keys({ firstName: 'John' }), _.keys({ firstName: 'Jane', lastName: 'Doe' }))
This gives me a result of ['firstName']
as expected, but I would like to find an easier or more efficient way, preferably vanilla Javascript.
Upvotes: 10
Views: 5922
Reputation: 11289
I know this question has already been answered but I wanted to offer an "underscore" way of doing it. I am also hoping that people will discuss the best "underscore" way of doing it here too.
var user1 = { firstName: 'John' }, user2 = { firstName: 'Jane', lastName: 'Doe' };
_.keys(_.pick(user1, _.keys(user2)))
that is my best shot at it, it doesn't reduct the underscore primitives from the original question so maybe this is the best you can do.
Here is the original question in my format for reference
_.intersection(_.keys(user1), _.keys(user2))
Upvotes: 0
Reputation: 25463
This will work for modern browsers:
function commonKeys(a, b) {
return Object.keys(a).filter(function (key) {
return b.hasOwnProperty(key);
});
};
// ["firstName"]
commonKeys({ firstName: 'John' }, { firstName: 'Jane', lastName: 'Doe' });
Upvotes: 5
Reputation: 303215
var common = [];
for (var key in obj2) if (key in obj1) common.push(key);
Edit for RobG: If you happen to be working in an environment that includes code that is not your own, and you do not trust the author(s) to have extended Object.prototype
correctly, then you might want to do:
var common = [];
for (var k in obj2) if (obj2.hasOwnProperty(k) && obj1.hasOwnProperty(k)) common.push(k);
However, as I have stated in the comments below, I have written an article (with an inflammatory title) about why I believe that this used to be good advice, but is good advice no longer:
http://phrogz.net/death-to-hasownproperty
Upvotes: 2
Reputation: 142921
Sure, just iterate through the keys of one object and construct an array of the keys that the other object shares:
function commonKeys(obj1, obj2) {
var keys = [];
for(var i in obj1) {
if(i in obj2) {
keys.push(i);
}
}
return keys;
}
Upvotes: 12