How to create an object from an Array of key-value pairs?

Object.fromEntries does the job. It was added to the language with EcmaScript2019.

If you don’t have support for that function, you could define it yourself with the following ES2015 code:

Object.fromEntries = arr => Object.assign({}, ...Array.from(arr, ([k, v]) => ({[k]: v}) ));

A nice thing is that this method does the opposite of Object.entries (ES2017), so now you can go back and forth between the object and array representation:

const arr = [['name', 'Bob'], ['age', 42], ['breakfast', 'eggs']];
const obj = Object.fromEntries(arr);
console.log(obj);
// ... and back:
const arr2 = Object.entries(obj);
console.log(arr2); // copy of the original array (omitting duplicate keys)
.as-console-wrapper { max-height: 100% !important; top: 0; }

ES6 Map

There is an alternative to plain objects for key/value pairs: Map.

Its constructor accepts the array-of-pairs format:

// Demo:
const arr = [['name', 'Bob'], ['age', 42], ['breakfast', 'eggs']];

const mp = new Map(arr);

// Get one particular value:
console.log(mp.get('age'));
// Get all the keys:
console.log(...mp.keys());
// Get all the values:
console.log(...mp.values());
// Get all the key/value pairs:
console.log(...mp.entries());

If you really need a plain object, then this is not useful, but a Map might present a viable alternative.

Leave a Comment