繁体   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