【发布时间】:2019-12-30 01:52:35
【问题描述】:
我正在开发一种过滤功能,该功能可以过滤呈现的数据列表。我的目标是能够使用用户选择的过滤器过滤数据对象,并返回与所有选定过滤器选项匹配的任何数据对象。
例如,这里是一个选定选项的模拟数组:
//This simulates a current filter options array
const filterOptions = ['Black', 'Green', '10.00', 'Wacky', 'false'];
这是我将与这些值进行比较的数据数组和对象属性的示例:
const data = {
games: [
{
name: 'Game1',
color: 'Black',
price: '1.00',
theme: 'Lucky',
licensed: true
},
{
name: 'Game2',
color: 'Pink',
price: '1.00',
theme: 'Multiple',
licensed: true
},
{
name: 'Game3',
color: 'Black',
price: '5.00',
theme: 'Crossword',
licensed: false
},
{
name: 'Game4',
color: 'Green',
price: '5.00',
theme: 'Lucky',
licensed: true
},
{
name: 'Game5',
color: 'Black',
price: '10.00',
theme: 'Wacky',
licensed: false
},
{
name: 'Game6',
color: 'Green',
price: '10.00',
theme: 'Wacky',
licensed: false
},
]
}
考虑到上面提到的模拟过滤器选项,我希望看到Game5 & Game6。两者都是10.00,或者是Black or Green,具有wacky 主题并且具有false 的license 值。
我的想法是,放弃使用“松散值”数组会更容易,并可能创建一个包含所选过滤器选项数组的对象,这些选项数组的属性是我的属性的名称打算将其与数据对象中的比较。
例如:
`const filterOptions =
{
color: ['Black', 'Green'],
price: ['10.00'],
theme: ['Wacky'],
licensed: [false]
}`
然后,我可以使用Object.keys(filterOptions) 之类的东西来循环选定的过滤器选项对象。我在这里唯一的事情是,似乎对于每场比赛,我都需要像这样循环filterOptions 对象:
const filterOptionsKeys = Object.keys(filterOptions);
const { games } = data;
games.forEach(game => {
//Game loop
console.log(game)
//Loop through filterOptions key array
filterOptionsKeys.forEach(key => {
console.log(key);
//Loop through each index of the filterOptions option arrays
filterOptions[key].forEach(option => {
console.log(option); //Assuming this is where I would make the comparisons
})
})
})
总的来说,对于games.forEach() 的每次迭代,我似乎都需要 2 个内部 forEach() 循环。我正在使用的数据对象返回超过 5000 个游戏对象,我觉得这种方法对于这么大的数据数组非常耗时。
我对我的处理方法感到很困惑,我担心我会以某种方式根深蒂固地做这件事,最终,这还不够。有没有我可以在lodash 中使用的东西来帮助做这样的事情?我有时会使用lodash 库,但我不确定如何将它应用于具有这么多匹配条件的东西。所以我总结这一切的问题是:解决这个问题的聪明方法是什么?
【问题讨论】:
标签: javascript arrays object ecmascript-6