简体   繁体   中英

Using underscore groupby to group an array of objects by more than one attribute

I want to group my JavaScript array of objects by two attributes of the object contained within.

I have tried underscores groupBy and it seems to accept only one attribute at a time.

_.groupBy([{'event_date':'2013-10-11', 'event_title':'Event 2'}, {'event_date':'2013-01-11', 'event_title':'Event 1'}], 'event_title')

My question is... is there a way to group an array of objects by two of its attributes.

Like in Ruby

[#<struct Event event_date=2013-10-11, event_title=Event 2>, #<struct Event  event_date=2013-01-11, event_title=Event 1>].group_by{|p| p.event_date and p.event_title}

From the fine manual :

groupBy _.groupBy(list, iterator, [context])

Splits a collection into sets, grouped by the result of running each value through iterator . If iterator is a string instead of a function, groups by the property named by iterator on each of the values.

So you can pass a function to _.groupBy and the results will be grouped by the result of that function. That just means that you need a function that will produce simple keys for your groups. Unfortunately, object keys in JavaScript are strings so you can't (reliably) use a function that returns an array of keys like you'd do in Ruby but you can kludge it a bit:

_(a).groupBy(function(o) {
    return o.event_title + '\x00' + o.other_key;
});

I'm guessing that '\\x00' won't appear in your event_title but you can use whatever delimiter works for your data.

Demo: http://jsfiddle.net/ambiguous/hwg3p/

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