How to Get Intersection of Keys of Two Objects with JavaScript?

Sometimes, we want to get intersection of keys of two objects with JavaScript.

In this article, we’ll look at how to get intersection of keys of two objects with JavaScript.

Get Intersection of Keys of Two Objects with 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.

For instance, we write:

const a = {
  x: undefined,
  y: 1,
  z: 2,
  a: 10,
  b: 20,
  e: 30
}
const b = {
  x: 0,
  y: 1,
  z: 2,
  a: 10,
  c: 20,
  d: 30
}

const intersect = (o1, o2) => {
  return Object.keys(o1).filter(k => k in o2)
}

console.log(intersect(a, b))

We have 2 objects a and b that have some overlapping keys.

Then we create the intersect function that takes 2 objects o1 and o2.

And we call Object.keys with o1 to return an array of key name strings in o1.

Then we call filter with a callback that checks if key k is on o2 with the in operator.

Therefore, from the console log, we see that the intersection of keys between o1 and o2 is ['x', 'y', 'z', 'a'].

Conclusion

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.