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

javascript

Solution

At the time of writing (2013) JavaScript objects / dictionaries / associative arrays don't have such a constructor natively.

As you said yourself, you can of course build your own function using for instance a functional approach using the `reduce` function as explained in one of the other answers. A classic for or newer forEach loop would also work, of course. But there isn't anything built-in.

Edit: It's 2019 and now we have Object.fromEntries, which will give you what you need.

Problem

In Python one can pass the `dict`1 constructor a sequence of key-value pairs: ``` >>> dict([['name', 'Bob'], ['age', 42], ['breakfast', 'eggs']]) {'age': 42, 'name': 'Bob', 'breakfast': 'eggs'} ``` I can't think of any way to do this sort of thing in JavaScript other than defining my own function for the purpose: ``` function pairs_to_object(pairs) { var ret = {}; pairs.forEach(function (p) { ret[p[0]] = p[1]; }); return ret; } ``` But I'm a JS noob... Is there anything built-in for this sort pairs-to-object conversion? 1 For the purposes of this question, I'm treating Python dicts as Python's counterpart of JS objects, although, of course the similarity is limited only to the fact that they are both key-value collections.

Original source

Related problems