For more tips like this, sign up to the weekly newsletter!

How to convert an Array of key-values to an Object

There is an Array of [key, value] elements:

const arr = [
  ["key1", "value1"],
  ["key2", "value2"]
];

How to convert it to an Object that has all the keys with the associated values?

Use Object.fromEntries

The easiest way is to use the relatively new addition, Object.fromEntries. This takes the above construct and converts it to an Object:

Object.fromEntries(arr)

// {"key1": "value1", "key2": "value2"}

This complements the Object.entries function that does the reverse:

Object.entries({key1: 5, key2: 5});

// [["key1", 5], ["key2", 5]]

Using these two together, you can easily map an object, converting each property to a new key-value tuple:

Object.fromEntries(
  Object.entries(
    {key1: 5, key2: 5}
  ).map(([k, v]) => [`${k}_new`, v + 1])
)

// {"key1_new":6,"key2_new":6}
Use Object.assign

Alternatively, you can convert the Array to multiple Objects having only one property, and then merge them into a single Object:

const obj = Object.assign({}, ...arr.map(([k, v]) => ({[k]: v})));

// {"key1": "value1", "key2": "value2"}

How does it work? Let's break it down!

arr.map converts each [k, v] elements to a {[k]: v} Object. This makes use of the dynamic property, as [k] is the value of k. In effect, this converts ["key1", "value1"] to {"key1": "value1"}.

Then the Array spread operator (...arr) converts the collection to individual parameters. After that is run, the parameters will be:

Object.assign({}, {"key1": "value1"}, {"key2": "value2"});

And finally, Object.assign modifies its first argument ({}) by merging the subsequent ones into it. Its result will be {"key1": "value1", "key2": "value2"}, which is exactly what we need.

Try it
References
Learn more: