What's the best way to convert a list of tuples to a dictionary in javascript?
One way is this:
var data = [['a',1], ['b',2],['c',3]]
var group_to_lengths = {}
data.forEach(function(d) {
group_to_lengths[d[0]] = d[1];
});
Is there a simpler or more idiomatic way of accomplishing the same thing? Perhaps like in python ( group_to_lengths = dict(data)
)?
I would recommend using Array.prototype.reduce
, which is more idiomatic for this case, like this
console.log(data.reduce(function(result, currentItem) {
result[currentItem[0]] = currentItem[1];
return result;
}, {}));
# { a: 1, b: 2, c: 3 }
But, if you use a functional programming library, like underscore.js , then it would be just a one-liner with _.object
, like this
console.log(_.object(data));
# { a: 1, b: 2, c: 3 }
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.