json 如何在嵌套对象中动态访问属性,以便在Vue 3中进行排序?

6psbrbz9  于 2023-08-08  发布在  其他
关注(0)|答案(1)|浏览(82)

我试图通过动态选择属性来对表进行排序。我有一个对象列表:

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'”不起作用,

dddzy1tm

dddzy1tm1#

动态生成排序函数:

const sortFn = new Function('a, b', `
  a = (a.${sortBy} || '').toLowerCase();
  b = (b.${sortBy} || '').toLowerCase();
  return a === b ? 0 : a > b ? 1 : -1;
`);

return Products.sort(sortFn);

字符串

相关问题