1

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))?

1
  • The concept dictionary in JS does not exist. In JS there is objects and arrays. Commented Feb 3, 2015 at 14:15

1 Answer 1

4

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 }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.