带有自定义逻辑的JSON数据排序

时间:2018-08-02 12:18:24

标签: javascript arrays sorting lodash

我有以下数据JSON数据,我必须对其进行优先级分组,然后组织分组的数据,以便前两个结果将是类型1,下一个1是类型2,下一个1将是类型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"
        }
    ]
   }

1 个答案:

答案 0 :(得分:0)

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

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