首页 文章

我如何用Lodash sortBy排序?

提问于
浏览
0

我有一个类似下面的数组,我正在尝试使用lodash按价格对数组中的项目进行排序,但我认为它不起作用 . 请告诉我这里有什么问题,根据lodash文档,它将采用数组并应返回已排序的数组 .

我的数据

var items= [
  {
    "total": 11,
    "productGroup": {
      "_id": "5834754f0acc770ce14b1378",
      "name": "Auto Biography",
      "description": "Yum",
      "type": "book"
    },    
    "_id": "58791af46c698c00475e7f41",    
    "price": 200,
    "sold": 0
  },
  {
    "total": 11,
    "productGroup": {
      "_id": "5834754f0acc770ce14b1378",
      "name": "Science Fiction",
      "description": "Yum",
      "type": "book"
    },    
    "_id": "58791af46c698c00475e7f41",    
    "price": 120,
    "sold": 0
  },
  {
    "total": 11,
    "productGroup": {
      "_id": "5834754f0acc770ce14b1378",
      "name": "Language",
      "description": "Yum",
      "type": "book"
    },    
    "_id": "58791af46c698c00475e7f41",    
    "price": 125,
    "sold": 0
  },
  {
    "total": 11,
    "productGroup": {
      "_id": "5834754f0acc770ce14b1378",
      "name": "Fiction",
      "description": "Yum",
      "type": "book"
    },    
    "_id": "58791af46c698c00475e7f41",    
    "price": 300,
    "sold": 0
  }
]

排序代码

items = _.sortBy(items, item=>{return item.price});

2 回答

  • 1

    很可能你使用的是旧版本的Lodash . 它适用于4.17.2,如下所示 .

    var items = [
      {
        "_id": "58791af46c698c00475e7f41",    
        "price": 200
      },
      {
        "_id": "58791af46c698c00475e7f41",    
        "price": 120
      },
      {
        "_id": "58791af46c698c00475e7f41",    
        "price": 125
      },
      {
        "_id": "58791af46c698c00475e7f41",    
        "price": 300
      }
    ];
    
    var results = _.sortBy(items, item => item.price);
    console.log(results);
    
    <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.2/lodash.min.js"></script>
    
  • 2

    根据source code,第二个参数应该是迭代数组 . 要解决此问题,您需要将匿名函数放在数组中,例如

    items = _.sortBy(items, [item=>{return item.price}]);
    

相关问题