我必须根据状态属性
对对象数组进行排序例如,我有以下数组
[
{userName:"One", status:"Live"},
{userName:"Two", status:"Rejected"},
{userName:"Three", status:"To Do"},
{userName:"Four", status:"Verify"},
{userName:"Five", status:"Received"},
{userName:"Six", status:"In Progress"}
]
排序后,我需要一个看起来像
的数组[
{userName:"Three", status:"To Do"},
{userName:"Five", status:"Received"},
{userName:"Six", status:"In Progress"},
{userName:"Two", status:"Rejected"},
{userName:"Four", status:"Verify"},
{userName:"One", status:"Live"}
]
需要根据其状态属性按以下顺序对项目进行排序
可以有多个具有相同状态的项目。
答案 0 :(得分:3)
您可以按顺序定义状态数组,然后使用状态'用于对数组进行排序的索引。
let status = {
'To Do': 1,
'Received': 2,
'In Progress': 3,
'Rejected': 4,
'Verify': 5,
'Live': 6
};
let data = [{
userName: "One",
status: "Live"
},
{
userName: "Two",
status: "Rejected"
},
{
userName: "Three",
status: "To Do"
},
{
userName: "Four",
status: "Verify"
},
{
userName: "Five",
status: "Received"
},
{
userName: "Six",
status: "In Progress"
}
];
data = data.sort((a, b) => status[a.status] - status[b.status]);
console.log(data);