我正在尝试按name
对以下对象进行排序。我希望列表按以下方式排序1(balloon
2(term
3(instalment
。
loanAdjustmentList = [
{
"description": "Restructure Option",
"name": "instalment",
"restructureAllowed": "N",
"reason": "Due to the status of your account we are unable to process your request. Please contact 0860 669 669 for more information",
"reasonCode": "1"
},
{
"description": "Restructure Option",
"name": "term",
"restructureAllowed": "N",
"reason": "Due to the status of your account we are unable to process your request. Please contact 0860 669 669 for more information",
"reasonCode": "1"
},
{
"description": "Restructure Option",
"name": "balloon",
"restructureAllowed": "N",
"reason": "Due to the status of your account we are unable to process your request. Please contact 0860 669 669 for more information",
"reasonCode": "1"
}
]
知道我能试试什么吗?
您希望对数组进行排序。
您只需要编写一个将另一个对象用作映射的排序函数。
const order = ["balloon", "installment", "term"]
loanAdjustmentList.sort((el1, el2) => {
if (order.indexOf(el1.name) < order.indexOf(el2.name) {
return -1;
} else (order.indexOf(el1.name) > order.indexOf(el2.name) {
return 1;
} else {
return 0;
}
});
当然,这是假设它们只是有问题的三个选项之一。如果您有任何其他名称类型,它可能会引发错误。
我已经包含了name
元素可能相同的可能性,这将允许对3个以上的选项进行排序。
如果您的意思是按照提到的三个名称排序,您可以尝试以下操作:
let loanAdjustmentList = [
{
"description": "Restructure Option",
"name": "instalment",
"restructureAllowed": "N",
"reason": "Due to the status of your account we are unable to process your request. Please contact 0860 669 669 for more information",
"reasonCode": "1"
},
{
"description": "Restructure Option",
"name": "term",
"restructureAllowed": "N",
"reason": "Due to the status of your account we are unable to process your request. Please contact 0860 669 669 for more information",
"reasonCode": "1"
},
{
"description": "Restructure Option",
"name": "balloon",
"restructureAllowed": "N",
"reason": "Due to the status of your account we are unable to process your request. Please contact 0860 669 669 for more information",
"reasonCode": "1"
}
]
loanAdjustmentList = [
...loanAdjustmentList.filter(x => x.name === 'balloon'),
...loanAdjustmentList.filter(x => x.name === 'term'),
...loanAdjustmentList.filter(x => x.name === 'instalment')
];
console.log(loanAdjustmentList);