admin管理员组文章数量:1391929
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}
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}
Share
Improve this question
edited Jul 26, 2013 at 16:49
asked Jul 26, 2013 at 16:39
user365916user365916
1
- 2 For those of us not familiar with the Ruby function, can you give an example of what output you're looking for? – freejosh Commented Jul 26, 2013 at 16:55
1 Answer
Reset to default 5From 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/ambiguous/hwg3p/
版权声明:本文标题:javascript - Using underscore groupby to group an array of objects by more than one attribute - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744718880a2621573.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论