我试图通过动态选择属性来对表进行排序。我有一个对象列表:
Products : {id: 1, Name: 'Ball', CategoryId: 1, Category: {id:1, Name:'Toy'}, Price:2},
{id: 2, Name: 'Plane', CategoryId: 1, Category: {id:1, Name:'Toy'}, Price:5},
{id: 3, Name: 'Ruler', CategoryId: 2, Category: {id:2, Name:'SchoolSupplies'}, Price:1},
{id: 4, Name: 'Pencil', CategoryId: 2, Category: {id:2, Name:'SchoolSupplies'}, Price:1},
{id: 2, Name: 'Balloon', CategoryId: 1, Category: {id:1, Name:'Toy'}, Price:5},
字符串
现在我尝试通过发送propertyname来排序表,如下所示:
@click="sortBy='Name'" etc
return Products.sort((a, b) => {
var a = a[sortBy] ? a[sortBy].toLowerCase() : a[sortBy];
var b = b[sortBy] ? b[sortBy].toLowerCase() : b[sortBy];
return a === b ? 0 : a > b ? 1 : -1;
});
型
排序函数对嵌套属性以外的属性起作用。所以我的问题是,我应该通过点击访问Category.Name?
我试过@click=“sortBy ='Category. Name'”不起作用,@click=“sortBy ='Category [Name]'”不起作用,@click=“sortBy ='Category [0]. Name'”不起作用,
1条答案
按热度按时间dddzy1tm1#
动态生成排序函数:
字符串