admin管理员组

文章数量:1327674

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>

本文标签: javascriptMultiple version of keyBy in lodash (Group values sharing a key as an array)Stack Overflow