如何使用lodash orderBy对具有深层嵌套属性的对象数组进行排序? [英] How to sort array of objects with deep nested properties using lodash orderBy?
问题描述
这是推荐使用lodash中的orderBy的方法
This is the recommended way of using orderBy from lodash
const data = _.orderBy(array_of_objects, ['type','name'], ['asc', 'desc']); - instead of keys
有没有办法做这样的事情?我可以像这样 ['type.id','name.entry']
一样将键路径作为字符串数组传递,而不是对象键 ['type','name']
?
is there a way to do something like this?
instead of object keys ['type','name']
can I pass key paths as string array like this ['type.id','name.entry']
?
因此,预期结果将是基于深度值的排序数组.
So that the expected result would be a sorted array based on deep values.
const data = _.orderBy(array_of_objects, ['type.id','name.entry'], ['asc', 'desc']); - instead of keys
我问这个问题是因为我们可以使用lodash _.get()这样访问对象的深层属性.
I am asking this because we can access an objects deep properties using lodash _.get() like this.
_.get(object, 'a[0].b.c');
// => 3
因此必须有一种使用_.orderBy()的方法
So there must be a way of doing this with _.orderBy()
注意事项:如果在香草js中可以做到这一点,请也建议这样做.
NB If there is a way of doing this in vanilla js, please suggest that also.
目前,在我的情况下,对于传递给 ['type.id','name.entry']
的每个键,都不会进行排序.
Currently in my case this is not getting sorted for every keys I pass ['type.id','name.entry']
only either of one is working.
如果无法实现,请建议如何基于多个深度嵌套的props(作为字符串路径传递)基于深度嵌套的props对数组对象进行排序
推荐答案
orderBy 确实接受回调,如果需要基于多个属性进行排序,则可以是函数列表.此语法基于Lodash 4.x.
orderBy does accept a callback, and this can be a list of functions if you need to order based on multiple attributes. This syntax is based on Lodash 4.x.
// for ordering based on a single attribute
const orderedData = _.orderBy(arrayOfObject, item => item.id, ['desc']);
// for ordering based on multiple attributes
const orderedData = _.orderBy(arrayOfObject, [
item => item.id,
item => item.entry,
], ['desc', 'asc']);
下面是一个示例,说明如何根据每个对象内的嵌套属性进行排序:
Here's an example of how you might sort based on a nested attribute within each object:
const items = [
{
id: 1,
entry: 'a',
nested: { val: 5 },
},
{
id: 5,
entry: 'five',
nested: { val: 1 },
},
{
id: 3,
entry: 'three',
nested: { val: 2 },
},
{
id: 2,
entry: 'two',
nested: { val: 3 },
},
{
id: 4,
entry: 'four',
nested: { val: 4 },
},
];
const nestedValueComparator = item => _.get(item, 'nested.val');
const nestedData = _.orderBy(items, nestedValueComparator, ['asc']);
这篇关于如何使用lodash orderBy对具有深层嵌套属性的对象数组进行排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!