【问题标题】:sort javascript object by sub value [duplicate]按子值对javascript对象进行排序[重复]
【发布时间】:2020-07-23 08:46:59
【问题描述】:

我已经尝试了几个小时使用“orderKey”字段对多维对象进行排序。 不幸的是,我无法根据我在互联网上找到的大量示例对其进行排序。

我的对象(简化):

{
"entry1": {
    "id"          : 1,
    "title"       : "Title",
    "shortDesc"   : "description",
    "price"       : 5,
    "isOnline"    : true,
    "orderKey"    : 2,
},
"entry2": {
 "id"             : 1,
    "title"       : "Title",
    "shortDesc"   : "description",
    "price"       : 10,
    "isOnline"    : true,
    "orderKey"    : 7,
},
...

我希望能够按“orderKey”(asc/desc)对对象进行排序。

如果能得到一些帮助,我将不胜感激。

编辑:我也找到了linked 帖子,但我无法使其适用于我的示例。

【问题讨论】:

    标签: javascript sorting object


    【解决方案1】:
    // define sort functions for ascending or descending
    const sortAscending = (a, b) => a[1].orderKey < b[1].orderKey ? -1 : 1
    const sortDescending = (a, b) => a[1].orderKey > b[1].orderKey ? -1 : 1
    
    // define function to sort the object that accepts an object and a toggle for ascending or descending order
    const sortObject = (obj, ascending = true) => {
        // convert the object into an array of key value pairs
        return Object.entries(obj)
            // sort the array in the direction specified by the toggle
            .sort(ascending ? sortAscending : sortDescending)
            // use reduce to convert the array of key values back to an object
            .reduce((memo, [key, value]) => ({ ...memo, [key]: value }), {})
    }
    
    // call the object sorting function with data
    sortObject({
        "entry1": {
            "id"          : 1,
            "title"       : "Title",
            "shortDesc"   : "description",
            "price"       : 5,
            "isOnline"    : true,
            "orderKey"    : 2
        },
        "entry2": {
            "id"          : 1,
            "title"       : "Title",
            "shortDesc"   : "description",
            "price"       : 10,
            "isOnline"    : true,
            "orderKey"    : 7
        }
    }, false) // use true for ascending
    

    【讨论】:

      猜你喜欢
      • 2011-11-16
      • 2012-01-17
      • 1970-01-01
      • 2014-08-25
      • 1970-01-01
      • 2018-02-18
      • 2014-01-25
      • 2021-04-23
      • 2023-02-05
      相关资源
      最近更新 更多