简体   繁体   English

如何使用 lodash orderBy 对具有深层嵌套属性的对象数组进行排序?

[英]How to sort array of objects with deep nested properties using lodash orderBy?

This is the recommended way of using orderBy from lodash这是从 lodash 使用 orderBy 的推荐方式

 const data = _.orderBy(array_of_objects, ['type','name'], ['asc', 'desc']); - instead of keys 

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'] ?而不是 object 键['type','name']我可以像这样['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 

I am asking this because we can access an objects deep properties using lodash _.get() like this.我问这个是因为我们可以像这样使用 lodash _.get() 访问对象的深层属性。

_.get(object, 'a[0].b.c');
// => 3

So there must be a way of doing this with _.orderBy()所以必须有一种方法可以使用 _.orderBy()

NB If there is a way of doing this in vanilla js, please suggest that also.注意如果在香草js中有这样做的方法,请也提出建议。

Currently in my case this is not getting sorted for every keys I pass ['type.id','name.entry'] only either of one is working.目前在我的情况下,这并没有对我传递的每个键进行排序['type.id','name.entry']只有其中一个正在工作。

If this is not possible please suggest how can I sort an array objects with deeply nested props based on multiple deeply nested props(passed as string paths)如果这不可能,请建议我如何根据多个深度嵌套的道具(作为字符串路径传递)对具有深度嵌套道具的数组对象进行排序

orderBy does accept a callback, and this can be a list of functions if you need to order based on multiple attributes. orderBy确实接受一个回调,如果您需要基于多个属性进行排序,这可以是一个函数列表。 This syntax is based on Lodash 4.x.此语法基于 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:下面是一个示例,说明如何根据每个 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']);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM