Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to get intersection of keys of two objects?

I have two object literals like so:

var firstObject = {     x: 0,     y: 1,     z: 2,      a: 10,     b: 20,     e: 30 }  var secondObject = {     x: 0,     y: 1,     z: 2,      a: 10,     c: 20,     d: 30 } 

I want to get the intersection of the keys these two object literals have like so:

var intersectionKeys  = ['x', 'y', 'z', 'a'] 

I can obviously do a loop and see if a key with the same name exists in the other object, but I am wondering if this would be a good case for some functional programming and map / filter / reduce usage? I myself have not done that much functional programming, but I have a feeling, that there could exist a clean and clever solution for this problem.

like image 215
Swiffy Avatar asked Dec 21 '15 09:12

Swiffy


People also ask

How to get intersection of two objects in JavaScript?

To get intersection of keys of two objects with JavaScript, we can use the Object. keys method to get the keys of an object. Then we can use the JavaScript array filter method to get an array of keys that exist in both objects.

How do you find the key of an object?

Use object. keys(objectName) method to get access to all the keys of object. Now, we can use indexing like Object. keys(objectName)[0] to get the key of first element of object.


1 Answers

A solution without indexOf.

var firstObject = { x: 0, y: 1, z: 2, a: 10, b: 20, e: 30 },      secondObject = { x: 0, y: 1, z: 2, a: 10, c: 20, d: 30 };    function intersection(o1, o2) {      return Object.keys(o1).concat(Object.keys(o2)).sort().reduce(function (r, a, i, aa) {          if (i && aa[i - 1] === a) {              r.push(a);          }          return r;      }, []);  }    document.write('<pre>' + JSON.stringify(intersection(firstObject, secondObject), 0, 4) + '</pre>');

Second attempt with O(n).

var firstObject = { x: 0, y: 1, z: 2, a: 10, b: 20, e: 30 },      secondObject = { x: 0, y: 1, z: 2, a: 10, c: 20, d: 30 };    function intersection(o1, o2) {      return Object.keys(o1).filter({}.hasOwnProperty.bind(o2));  }    document.write('<pre>' + JSON.stringify(intersection(firstObject, secondObject), 0, 4) + '</pre>');
like image 153
Nina Scholz Avatar answered Sep 29 '22 09:09

Nina Scholz