最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Multiple version of keyBy in lodash? (Group values sharing a key as an array) - Stack Overflow

programmeradmin3浏览0评论

Is there a simple way to achieve this with lodash?

_.something([{a: 3, b: 4}, {a: 3, b: 5}, {a: 10}], 'a')

=> { 3: [ {a: 3, b: 4}, {a: 3, b: 5 } ], 10: [{ a: 10 }]}

That is, group all the values that share the same key together as an array under that key.

Is there a simple way to achieve this with lodash?

_.something([{a: 3, b: 4}, {a: 3, b: 5}, {a: 10}], 'a')

=> { 3: [ {a: 3, b: 4}, {a: 3, b: 5 } ], 10: [{ a: 10 }]}

That is, group all the values that share the same key together as an array under that key.

Share Improve this question asked Sep 9, 2018 at 11:20 Steve BennettSteve Bennett 127k45 gold badges186 silver badges243 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 9

You could use _.groupBy for grouping by a given key.

Creates an object posed of keys generated from the results of running each element of collection thru iteratee. The order of grouped values is determined by the order they occur in collection. The corresponding value of each key is an array of elements responsible for generating the key. The iteratee is invoked with one argument: (value).

console.log(_.groupBy([{ a: 3, b: 4 }, { a: 3, b: 5 }, { a: 10 }], 'a'));
.as-console-wrapper { max-height: 100% !important; top: 0; }
<script src="https://cdnjs.cloudflare./ajax/libs/lodash.js/4.15.0/lodash.min.js"></script>

发布评论

评论列表(0)

  1. 暂无评论