您能告诉如何使用orderBy来处理具有各种字段类型(字符串和数字)的对象吗? 例如
_.orderBy([{a: 3}, {a: 2}, {a: 'a'}, {a: 1}, {a: 'c'}, {a: 'b'}], ['a'], ['asc'])
我有
[{"a":2},{"a":3},{"a":"a"},{"a":1},{"a":"b"},{"a":"c"}]
但我怎么能得到像
这样的东西[{"a":1},{"a":2},{"a":3},{"a":"a"},{"a":"b"},{"a":"c"}]
答案 0 :(得分:0)
比较值的_.toString
结果。
var input = [{a: 3}, {a: 2}, {a: 'a'}, {a: 1}, {a: 'c'}, {a: 'b'}],
output = _.sortBy(input, o => _.toString(o['a']));
console.log(output);
<script src="https://cdn.jsdelivr.net/lodash/4.13.1/lodash.min.js"></script>
如果要先根据类型进行分区,请使用_.groupBy
然后排序。
var input = [{a: 3}, {a: 2}, {a: 'a'}, {a: 1}, {a: 'c'}, {a: 'b'}];
var output = _(input)
.groupBy(o => typeof o['a'])
.map(a => _.sortBy(a, 'a'))
.flatten()
.value();
console.log(output);
<script src="https://cdn.jsdelivr.net/lodash/4.13.1/lodash.min.js"></script>