我有以下数据:
const products = [{
name: "Product 1",
options: [
{
id: 1,
optionName: "Color",
value: "Red"
},
{
id: 2,
optionName: "Size",
value: "Small"
}
]},
{
name: "Product 2",
options: [
{
id: 1,
optionName: "Color",
value: "Red"
},
{
id: 2,
optionName: "Size",
value: "Large"
}
]}];
我有一个过滤器对象,它是动态创建的:let selectedFilters = {"Color":"Red", "Size":"Small"};
我只想获取满足 selectedFilters 对象中指定的所有条件的产品。在示例中,我应该只得到“产品 1”这是我迄今为止尝试过的,但这些都不是我需要的:
let filteredProducts = [];
let keys = Object.keys(selectedFilters);
keys.forEach(function(filterKey) {
let f = _.filter(products, function(o) {
let flag = false;
let searchFilterKey = selectedFilters[filterKey];
let index = o.options.findIndex(o=> o.optionName == filterKey && o.value == searchFilterKey);
if (index > 0)
return o;
});
filteredProducts = f;
});
products.filter(p =>
Object.keys(selectedFilters).every(k =>
{
return p.options.filter(o => o.optionName == k && o.value == selectedFilters[k]);
}));
最佳答案
您可以在数组中获取过滤器的值并运行具有匹配条件的每个函数。由于“值”是此处的重要属性,因此使用它来针对选定过滤器运行其值。
如果您是标准的一部分,则对键执行相同操作
const products = [{
name: "Product 1",
options: [{
id: 1,
optionName: "Color",
value: "Red"
},
{
id: 2,
optionName: "Size",
value: "Small"
}
]
},
{
name: "Product 2",
options: [{
id: 1,
optionName: "Color",
value: "Red"
},
{
id: 2,
optionName: "Size",
value: "Large"
}
]
}
]
let selectedFilters = {
"Color": "Red",
"Size": "Small"
};
const arrFilterValues = Object.values(selectedFilters);
const arrFilterKeys = Object.keys(selectedFilters);
const result = products.filter(x => {
return x.options.every(y=> arrFilterValues.includes(y['value']) && arrFilterKeys.includes(y['optionName']))
})
console.log(result)
关于javascript - 如何使用 Lodash 或纯 javascript 使用动态过滤器过滤嵌套对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63459640/