【问题标题】:JSON data sorting with custom logic使用自定义逻辑对 JSON 数据进行排序
【发布时间】:2019-01-10 05:13:01
【问题描述】:

我有以下数据 JSON 数据,我必须按优先级分组,然后按顺序组织分组数据,其中前两个结果将是类型 1,下一个结果是类型 2,下一个结果是类型 3,然后重复

{
    "list": [{
            "_id": "555ed01e0f398a7b1436bf05",
            "type": 1,
            "priority": 1,
            "name": "John"
        },
        {
            "_id": "555ed01e0f398a7b1436bf07",
            "type": 2,
            "priority": 1,
            "name": "Jack"
        },
        {
            "_id": "555ed01e0f398a7b1436bf09",
            "type": 1,
            "priority": 1,
            "name": "Smith"
        },
        {
            "_id": "555ed01e0f398a7b1436bf09",
            "type": 2,
            "priority": 1,
            "name": "Kiles"
        },
        {
            "_id": "555ed01e0f398a7b1436bf11",
            "type": 1,
            "priority": 1,
            "name": "Stacy"
        },
        {
            "_id": "555ed01e0f398a7b1436bf13",
            "type": 1,
            "priority": 2,
            "name": "Stacy"
        }
    ]
}

我正在尝试通过使用 lodash 来做到这一点

_.chain(myArray).groupBy("priority").map(item=> _.groupBy(item,"offerType")).value()

这给了我相应的分组和排序结果,但现在我被困在结果中的自定义排序中。如何在列表中实现所需的顺序。

我正在寻找的结果

 {
    "list": [{
            "_id": "555ed01e0f398a7b1436bf05",
            "type": 1,
            "priority": 1,
            "name": "John"
        },
        {
            "_id": "555ed01e0f398a7b1436bf09",
            "type": 1,
            "priority": 1,
            "name": "Smith"
        },
        {
            "_id": "555ed01e0f398a7b1436bf07",
            "type": 2,
            "priority": 1,
            "name": "Jack"
        },
        {
            "_id": "555ed01e0f398a7b1436bf11",
            "type": 1,
            "priority": 1,
            "name": "Stacy"
        },
        {
            "_id": "555ed01e0f398a7b1436bf09",
            "type": 2,
            "priority": 1,
            "name": "Kiles"
        },
        {
            "_id": "555ed01e0f398a7b1436bf13",
            "type": 2,
            "priority": 2,
            "name": "Stacy"
        }
    ]
   }

【问题讨论】:

  • 不是 JSON。
  • 正如乔治所说,它不是 JSON,而且,您在此处发布的数组中的对象都有错误,缺少 ,: 和最后一个无效的类型值一。
  • @CalvinNunes 抱歉我更正了 JSON
  • @BipinChandraTripathi 我不明白您要以哪种方式订购数组的逻辑。是按优先级还是按类型或两者兼而有之?看起来不像是你想要的结果。

标签: javascript arrays sorting lodash


【解决方案1】:

查看结果,在我看来,您只想对数据进行排序,而不是分组:

result = _.chain(myArray).sortBy("priority", "type")

【讨论】:

  • 我想在组内排序,排序将是前两个结果将是类型 1,下一个结果将是类型 2,然后在组内重复
  • 你展示的结果数据没有分组,只是排序而已。结果数据对吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-04-26
  • 1970-01-01
  • 2018-05-12
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多