Determine if 2 javascript objects have strictly the same properties I need to compare 2 objects to determine if they have strictly the same properties.

This is what I came up with so far:


import isEmpty from 'lodash/isEmpty';

const shallowPropertiesMatch = (firstObject, secondObject) =&gt; {
  if (isEmpty(firstObject) || isEmpty(secondObject)) return false;

  const firstObjectKeys = Object.keys(firstObject);
  const secondObjectKeys = Object.keys(secondObject);

  if (firstObjectKeys.length !== secondObjectKeys.length) return false;
  if (!firstObjectKeys.every(value =&gt; secondObjectKeys.includes(value))) return false;

  return true;
};




I was wondering if there is a more efficient, elegant or simpler way of doing this?
By this condition, the function returns false when both objects are empty:


if (isEmpty(firstObject) || isEmpty(secondObject)) return false;



I would expect true in this case, and rewrite the condition as:

if (isEmpty(firstObject) != isEmpty(secondObject)) return false;


That is, return false if one of them is empty while the other is not.

In fact, this special treatment is not even necessary, because the rest of the function naturally handles the case of empty objects.




  I was wondering if there is a more efficient, elegant or simpler way of doing this?


The current implementation is not efficient,
because of this step:


if (!firstObjectKeys.every(value =&gt; secondObjectKeys.includes(value))) return false;



The problem is that secondObjectKeys is an array,
and therefore .includes does a linear lookup.
You can improve the linear-time lookup to constant-time lookup by converting secondObjectKeys to a set.