简体   繁体   English

使用 Lodash 按值对对象数组进行排序

[英]use Lodash to sort array of object by value

I am trying to sort an array by 'name' value (using Lodash).我正在尝试按“名称”值对数组进行排序(使用 Lodash)。 I used the Lodash docs to create the solution below however .orderBy doesn't seem to be having any affect at all.我使用 Lodash 文档来创建下面的解决方案,但是 .orderBy 似乎根本没有任何影响。 Can anyone shed some light on the correct way to sort array?任何人都可以阐明对数组进行排序的正确方法吗?

Chars Array字符数组

[  
   {  
      "id":25,
      "name":"Anakin Skywalker",
      "createdAt":"2017-04-12T12:48:55.000Z",
      "updatedAt":"2017-04-12T12:48:55.000Z"
   },
   {  
      "id":1,
      "name":"Luke Skywalker",
      "createdAt":"2017-04-12T11:25:03.000Z",
      "updatedAt":"2017-04-12T11:25:03.000Z"
   }
]

Function Code功能代码

 var chars = this.state.characters;

 _.orderBy(chars, 'name', 'asc'); // Use Lodash to sort array by 'name'

 this.setState({characters: chars})

This method orderBy does not change the input array, you have to assign the result to your array :此方法orderBy不会更改输入数组,您必须将结果分配给您的数组:

var chars = this.state.characters;

chars = _.orderBy(chars, ['name'],['asc']); // Use Lodash to sort array by 'name'

 this.setState({characters: chars})

You can use lodash sortBy ( https://lodash.com/docs/4.17.4#sortBy ).您可以使用 lodash sortBy ( https://lodash.com/docs/4.17.4#sortBy )。

Your code could be like:你的代码可能是这样的:

const myArray = [  
   {  
      "id":25,
      "name":"Anakin Skywalker",
      "createdAt":"2017-04-12T12:48:55.000Z",
      "updatedAt":"2017-04-12T12:48:55.000Z"
   },
   {  
      "id":1,
      "name":"Luke Skywalker",
      "createdAt":"2017-04-12T11:25:03.000Z",
      "updatedAt":"2017-04-12T11:25:03.000Z"
   }
]

const myOrderedArray = _.sortBy(myArray, o => o.name)

If you need to sort by date, you could use this solution:如果需要按日期排序,可以使用以下解决方案:

orderBy(employeePensions, (a) => new Date(a.startDate), ['asc']) // or 'desc'

If you are using moment library, then:如果您使用的是moment库,则:

orderBy(employeePensions, (a) => moment(a.startDate), 'asc')

Ps Note that the lodash doesn't sort dates in string format, so you must convert it to Date object. Ps 请注意, lodash不会以字符串格式对日期进行排序,因此您必须将其转换为 Date 对象。

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

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