How to Create an Array of Key/Value Pairs From a JavaScript Object?

Let's suppose you have an object like the following:

const obj = { foo: 'bar', baz: 'qux' };

From which you wish to create an array of key/value pairs like so:

const pairs = [
    ['foo', 'bar'],
    ['baz', 'qux'],
];

To achieve that, you can use any of the following methods (depending on the version of ES you support):

Using Object.entries()

Introduced in ES8, you can use Object.entries() to create an array of key/value pairs from an object, for example, like so:

// ES8+
const pairs = Object.entries(obj);

console.log(pairs); // [['foo', 'bar'], ['baz', 'qux']]

For versions prior to ES8, you can use a polyfill for Object.entries(), or alternatively use the for...in loop.

Using the for...in Loop

You can use the for...in loop to iterate over the object properties and add the object's key/value pairs to an array in the following way:

const obj = { foo: 'bar', baz: 'qux' };
const pairs = [];

for (const key in obj) {
  pairs.push([key, obj[key]]);
}

console.log(pairs); // [['foo', 'bar'], ['baz', 'qux']]

The for...in loop was introduced in ES1. Therefore, it has great browser support, so compatibility won't be much of an issue.

Please note that by default the for...in loop iterates over all enumerable properties of an object (including the inherited ones). If this is not the behavior you desire, then you can consider adding a check with the Object.prototype.hasOwnProperty() method inside the for...in loop to exclude the inherited properties.


This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.