简体   繁体   中英

How to sort array of objects with deep nested properties using 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 

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 

I am asking this because we can access an objects deep properties using lodash _.get() like this.

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

So there must be a way of doing this with _.orderBy()

NB If there is a way of doing this in vanilla js, please suggest that also.

Currently in my case this is not getting sorted for every keys I pass ['type.id','name.entry'] only either of one is working.

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. 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']);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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