简体   繁体   中英

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.

您可以使用reduce

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

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM