1

I have an array that looks something like this: [["key1", "value1"], ["key2", "value2"]]. I want a dictionary that looks like this: {"key1": "value1", "key2": "value2"}. In Python, I could just pass the array to the dict initializer. Is there some equivalent way of doing this in Javascript, or am I stuck initializing an empty dictionary and adding the key/value pairs to the dictionary one at a time?

mway
  • 615
  • 5
  • 14

2 Answers2

2

It's actually really easy with Array#reduce:

var obj = yourArray.reduce(function(obj, entry) {
    obj[entry[0]] = entry[1];
    return obj;
}, {});

Array#reduce loops through the entries in the array, passing them repeatedly into a function along with an "accumulator" you initialize with a second argument.

Or perhaps Array#forEach would be clearer and more concise in this case:

var obj = {};
yourArray.forEach(function(entry) {
    obj[entry[0]] = entry[1];
});

Or there's the simple for loop:

var obj = {};
var index, entry;
for (index = 0; index < yourArray.length; ++index) {
    entry = yourArray[index];
    obj[entry[0]] = entry[1];
}
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
1

Assuming you have a pairs variable, you can use a map() function workaround (not very elegant, as map is supposed to be used in other scope) :

var convertedDict = {};
pairs.map(function(pair) {
    convertedDict[pair[0]] = pair[1];
});
Cristik
  • 30,989
  • 25
  • 91
  • 127