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

Create an array of key/value pairs from an object in JavaScript

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 loop.

Using the Loop

You can use the 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 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 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 loop to exclude the inherited properties.

Hope you found this post useful. It was published . Please show your love and support by sharing this post.