turtle
turtle

Reputation: 8093

Generate a hash from a list of hashes

I'm new to JS and I'm trying to figure out how I can take a list of hashes and convert them to one hash. For example,

lst = [{"a": 10, "b": 2}, {"a": 10, "c": 5}, {"a": 10, "b": 2, "d": 20}]

to:

hash = {"a": 10, "b": 2, "c": 5, "d": 20}

What is the best way to do this? I was trying to use underscore's map in some way, but I'm not sure that is best approach.

Upvotes: 1

Views: 175

Answers (1)

Denys Séguret
Denys Séguret

Reputation: 382454

You could use reduce :

var hash = lst.reduce(function(r,o){ for (var k in o) r[k]=o[k]; return r }, {});

Upvotes: 2

Related Questions