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

2022-08-30 04:03:15

我正在尝试按“名称”值(使用Lodash)对数组进行排序。我使用Lodash文档创建了下面的解决方案,但是.orderBy似乎根本没有任何影响。任何人都可以阐明对数组进行排序的正确方法吗?

字符数组

[  
   {  
      "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"
   }
]

函数代码

 var chars = this.state.characters;

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

 this.setState({characters: chars})

答案 1

此方法不会更改输入数组,您必须将结果分配给数组:orderBy

var chars = this.state.characters;

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

 this.setState({characters: chars})

答案 2

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

您的代码可能如下所示:

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)