Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find the common members of two Javascript objects

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.

  • Is there a better/easier way to do this with underscore?
  • Is there a better/easier way to do this without underscore (preferred)?
like image 715
sellmeadog Avatar asked Jun 03 '13 00:06

sellmeadog


People also ask

How to compare two objects in 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.

Can you have an array of objects in JavaScript?

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.


2 Answers

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' });
like image 159
Casey Chu Avatar answered Oct 26 '22 14:10

Casey Chu


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;
}
like image 20
Peter Olson Avatar answered Oct 26 '22 15:10

Peter Olson