【发布时间】:2021-03-08 23:02:24
【问题描述】:
我有一个下拉菜单,可以切换到 3 种状态 - 升序、降序和无。下拉列表重新排列我列表中的项目。
我的代码:
list.component.html
<div *ngFor="let item of items; index as i">
<ui-list-item
[body]=getItem(item)"
></ui-list-item>
</div>
list.component.ts
getItem(item){
const toggle = {Price: true, Active: false, Modifiers: true}
let list = [
{label:"Price", value:item.price}, // e.g. "$10.00"
{label:"Active", value:item.active}, // e.g. true
{label:"Position", value:item.position} // e.g. 1
{label:"Category", value:item.category} // e.g. "Food"
];
return list;
}
toggle中的值为true时,项目按升序排列。当toggle中的值为false时,按降序排列。
如何按照从左到右切换值的顺序实现排序功能? (例如,如果价格先于位置等)并且由于标签包含不同类型的值,我如何检测类型并进行相应的排序?
我找到了这个How to sort an array of objects with labels according to other array of labels?,但它似乎不起作用。
更新的答案(但仍然无效)
getItem(item){
const toggle = {Price: true, Active: false, Modifiers: true}
let list = [
{label:"Price", value:item.price}, // e.g. "$10.00"
{label:"Active", value:item.active}, // e.g. true
{label:"Position", value:item.position} // e.g. 1
{label:"Category", value:item.category} // e.g. "Food"
];
list = list.sort((a: any, b: any) => {
if (typeof toggle[a.label] === 'boolean') {
if (toggle[a.label]) return a.value - b.value;
else return b.value - a.value;
} else {
return 0;
}
});
return list;
}
是因为我没有检索整个列表进行排序吗?感谢您的帮助!
【问题讨论】:
标签: javascript arrays angular typescript sorting