Check if matching keys are equal

Viewed 60

I searched if this question is present here, but can't find it.

Say we have two objects and we want to check if the matching keys are equal, for example:

const style1 = {
    color: 'brown',
    backgroundColor: 'blue',
    border: '3px solid blue'
}

const style2 = {
    fontSize: '16px',
    padding: '10px',
    color: 'brown'
}

The result of something like:

isMatchingKeysEqual(style1, style2)

should return true

2 Answers

Iterate over the key / value pairs ("entries") of one object and check if any match the other via Array.prototype.some().

function isMatchingKeysEqual(obj1, obj2) {
  return Object.entries(obj1).some(([ key, val ]) =>
    obj2[key] === val)
}

const style1 = {
    color: 'brown',
    backgroundColor: 'blue',
    border: '3px solid blue'
}

const style2 = {
    fontSize: '16px',
    padding: '10px',
    color: 'brown'
}

console.log(isMatchingKeysEqual(style1, style2))

Note, this only works on an object with a depth of 1. If you needed to check complex objects with object or array values, you'd need to do something recursive.

I have been thinking about this problem for several days, and I believe I have a satisfactory solution.

I wanted to write a function that could take in n number of object arguments. So that it could be used for more than just two objects.

Here it is:

function areIntersectingKeysEqual(...objects) {
  return objects
    .map((object) => Object.keys(object))
    .sort((a, b) => a.length - b.length)
    .reduce((a, b) => a.filter((key) => b.includes(key)))
    .every((key) => objects.every((object) => object[key] === objects[0][key]));
}

Let me explain how it works.

At a high level, first we find the intersecting keys, then we determine if all intersecting keys are equal.

  1. Map all objects, returning an array of key arrays.
  2. Sort the lists according to length ascending (this is an optimization, shortest key list is filtered first)
  3. Reduce our lists of keys, filtering them by the condition that the next array includes that key. This is how we find intersecting keys.
  4. Now that we have a list of intersecting keys, we can determine if the keys are equal. For every key, check that the value in every object is equal.
  5. Finally, return the resulting boolean.

Here is how it is used.

function areIntersectingKeysEqual(...objects) {
  return objects
    .map((object) => Object.keys(object))
    .sort((a, b) => a.length - b.length)
    .reduce((a, b) => a.filter((key) => b.includes(key)))
    .every((key) => objects.every((object) => object[key] === objects[0][key]));
}

const style1 = {
  color: 'brown',
  backgroundColor: 'blue',
  border: '3px solid blue',
};

const style2 = {
  fontSize: '16px',
  padding: '10px',
  color: 'brown',
};

const style3 = {
  fontSize: '10px',
  color: 'blue',
};

areIntersectingKeysEqual(style1, style2);
//  true

areIntersectingKeysEqual(style1, style2, style3);
// false

Related