Categories
JavaScript Answers

How to check that two objects have the same set of property names with JavaScript?

Spread the love

To check that two objects have the same set of property names with JavaScript, we use the Object.keys method.

For instance, we write

const compareKeys = (a, b) => {
  const aKeys = Object.keys(a).sort();
  const bKeys = Object.keys(b).sort();
  return JSON.stringify(aKeys) === JSON.stringify(bKeys);
};

to define the compareKeys function.

In it, we get the keys of objects a and b with Object.keys in an array.

Then we sort both arrays with sort.

Then we convert both arrays to JSON strings with JSON.stringify and compare to see if they’re equal.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published.