簡體   English   中英

如何通過對象內的參數對對象數組進行排序?

[英]How can I sort a array of objects by a parameter inside an objects?

例如,我有一個后端返回的對象數組,位置為字符串。

[
    {
        "color": "red",
        "position": "SECOND"
    },
    {
        "color": "blue",
        "position": null
    },
    {
        "color": "green",
        "position": "FIRST"
    },
    {
        "color": "pink",
        "position": "THIRD"
    }
]

我需要通過鍵“位置”重新組織此數組,但我需要 mantein 所有對象,包括您原始位置中的空值(空值必須在具有位置的對象之后)。

[
    {
        "color": "green",
        "position": "FIRST"
    },
    {
        "color": "red",
        "position": "SECOND"
    },
    {
        "color": "pink",
        "position": "THIRD"
    },
    {
        "color": "blue",
        "position": null
    },
]

我嘗試使用帶有切片的可能位置的 map,但我的數組保持亂序。

有沒有辦法在“位置”字段中有不同的值?

你可以嘗試這樣的事情:

let test = [
    {
        "color": "red",
        "position": "SECOND"
    },
    {
        "color": "blue",
        "position": null
    },
    {
        "color": "green",
        "position": "FIRST"
    },
    {
        "color": "pink",
        "position": "THIRD"
    }
]


test.sort((a,b) => a.position > b.position ? 1 : -1)  //for ascending order

test.sort((a,b) => a.position > b.position ? -1 : 1)  //for descending order

不過巧合的是“第一”“第二”“第三”是按字母順序排列的

const input = [ { color: "red", position: "SECOND", }, { color: "blue", position: null, }, { color: "green", position: "FIRST", }, { color: "pink", position: "THIRD", }, { color: "yellow", position: "FOURTH", }, ]; const sortOrder = [ "first", "second", "third", "fourth", "fifth", "sixth", "seventh", "eighth", "ninth", "tenth", ]; function doCustomSort(a, b, customSortOrder) { if (a.position === null && b.position !== null) { return 1; } else if (a.position !== null && b.position === null) { return -1; } return ( sortOrder.indexOf(a.position.toLowerCase()) - sortOrder.indexOf(b.position.toLowerCase()) ); } console.log(input.sort((a, b) => doCustomSort(a, b, sortOrder)));

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM