【发布时间】:2021-04-23 08:34:07
【问题描述】:
我目前正在尝试在我的软件中构建一个过滤系统,这就是我在下面的内容,正如你所看到的,我正在使用eval(),并且想要一个我不需要使用@的解决方案987654324@,大家有什么建议吗?
const items = [{
Product: {
name: 'Hello',
which: 1
},
Finance: {
zero: 0
}
},
{
Product: {
name: 'Hello2',
which: 0
},
Finance: {
zero: 0
}
}];
const filterMenu = [{
name: 'text1',
filterKey: 'Finance.zero == 0',
subText: false
}, {
name: 'text3',
filterKey: 'Product.which == 0',
subText: false
}];
const filteredBy = [0, 1];
const filtered = items.filter(e => eval(filteredBy.map(item => "e." + filterMenu[item].filterKey).join(' && ')));
console.log(filtered);
【问题讨论】:
-
@Bergi - 这不会通过变量名动态访问属性,我想放置完整的过滤器参数,例如
Product.which == 0分配给对象,因为我将在管理仪表板中分配此逻辑。 -
只在菜单对象中存储函数,而不是字符串:
filterKey: arg => arg.Finance.zero == 0
标签: javascript dictionary filter eval