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?
-
possible duplication of stackoverflow.com/questions/26454655/…Paul Fitzgerald– Paul Fitzgerald2015-04-20 22:02:56 +00:00Commented Apr 20, 2015 at 22:02
-
@PaulFitzgerald: Nice one, you're right.T.J. Crowder– T.J. Crowder2015-04-20 22:10:44 +00:00Commented Apr 20, 2015 at 22:10
Add a comment
|
2 Answers
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];
}