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.
The _. isEqaul is property of lodash which is used to compare JavaScript objects. It is used to know whether two objects are same or not. For ex, there are two arrays with equal number of elements, properties and values are also same.
JavaScript variables can be objects. Arrays are special kinds of objects. Because of this, you can have variables of different types in the same Array.
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' });
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With