lodash - sort result of _.groupBy before creating an array with it
我正在使用lodash的groupBy按1到10的数字值对对象进行分组。让我们将属性称为" sort"
groupBy的结果看起来像
1 2 3 4 5 | { 1:[{sort:1,...}, ...], 2:[{sort:2,...}], ...]. ... } |
接下来,我使用Object.values(result)将其转换回二维数组,以双ngFor角度显示。
问题是我不能确定(可以吗?)对象的顺序是否正确。 groupBy是否以最适合的顺序创建密钥?
所以如果结果看起来像
1 2 3 4 5 6 | { 3:[...], 1:[...], 2:[...], ... } |
在将_groupBy结果推入数组之前如何对其进行预排序?
由于您的键是数字,因此
1 2 3 4 5 6 7 8 9 | const data = { 3:3, 1:1, 2:2, }; const result = Object.values(data); console.log(result); |
_.groupBy方法的文档中对此进行了非常明确的定义:
Creates an object composed 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).
如果您想订购这些,则需要在
我也很难信任JavaScript对象的迭代顺序。 我建议您通过使用lodash的
如果我正确地解释了您的问题,则将
1 | this.target_data = _.sortyBy(result, 'sort'); |
请查看此快速演示。