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

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

Let's suppose you have an array of key/value pairs like the following:

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

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

const obj = { 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.fromEntries()

In ES2019+, you can achieve that by using the Object.fromEntries() method in the following way:

// ES2019+
const obj = Object.fromEntries(pairs);

console.log(obj); // {foo: 'bar', baz: 'qux'}

Using a for Loop

To create an object from an array of key/value pairs, you can simply use a for loop in the following way:

const obj = {};

for (let i = 0; i < pairs.length; i++) {
    const currPair = pairs[i];
    obj[currPair[0]] = currPair[1];
}

console.log(obj); // {foo: 'bar', baz: 'qux'}

In ES6+, you can make this even more readable by using the array destructuring assignment, for example, like so:

// ES6+
const obj = {};

for (let i = 0; i < pairs.length; i++) {
    const [key, value] = pairs[i];
    obj[key] = value;
}

console.log(obj); // {foo: 'bar', baz: 'qux'}

Using Array.prototype.reduce()

Introduced in ES5, you can use Array.prototype.reduce() to create an object from an array of key/value pairs in the following way:

// ES5+
const objFromPairs = function(arr) {
    return arr.reduce(function(accumulator, value) {
        accumulator[value[0]] = value[1];
        return accumulator;
    }, {});
}

console.log(objFromPairs(pairs)); // {foo: 'bar', baz: 'qux'}

You can shorten it to a one-liner in ES6+ by using the arrow function in the following way:

// ES6+
const objFromPairs = (arr) => arr.reduce((acc, val) => (acc[val[0]] = val[1], acc), {});

console.log(objFromPairs(pairs)); // {foo: 'bar', baz: 'qux'}

The shorthand syntax works because of the comma operator, which evaluates the operands from left-to-right, and returns the last operand (which in this case is the accumulator in the reducer function).


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