How can I use lodash/underscore to sort by multiple nested fields?

前端 未结 7 1157
情话喂你
情话喂你 2021-02-03 21:51

I want to do something like this:

var data = [
    {
        sortData: {a: \'a\', b: 2}
    },
    {
        sortData: {a: \'a\', b: 1}
    },
    {
        sort         


        
7条回答
  •  [愿得一人]
    2021-02-03 22:28

    If you need to specify the sort direction, you can use _.orderBy with the array of functions syntax from Lodash 4.x:

    _.orderBy(data, [
      function (item) { return item.sortData.a; },
      function (item) { return item.sortData.b; }
    ], ["asc", "desc"]);
    

    This will sort first ascending by property a, and for objects that have the same value for property a, will sort them descending by property b.

    It works as expected when the a and b properties have different types.

    Here is a jsbin example using this syntax.

提交回复
热议问题