这是我的对象数组。我想通过在函数中传递查询来过滤对象。
const products = [{
name: "A",
color: "Blue",
size: 50
},
{
name: "B",
color: "Blue",
size: 60
},
{
name: "C",
color: "Black",
size: 70
},
{
name: "D",
color: "Green",
size: 50
}
];
我想要的输出将从我传递的查询中过滤出来,该查询可以是任何东西
{
name: "A",
color: "Blue",
size: 50
}, {
name: "C",
color: "Black",
size: 70
}
这是我要传递给函数的查询对象
const filter = {
color: ["Blue", "Black"],
size: [70, 50]
};
这是我的函数,可以将其分配给其他变量并将其用于进一步的操作
const filteredData = filterIt(products, filter);
答案 0 :(得分:1)
您可以获取过滤器对象的条目,并获取用于通过includes
检查的键和值。
const
filterBy = filter => o => Object.entries(filter).every(([k, v]) => v.includes(o[k])),
filterIt = (array, filter) => array.filter(filterBy(filter)),
products = [{ name: "A", color: "Blue", size: 50 }, { name: "B", color: "Blue", size: 60 }, { name: "C", color: "Black", size: 70 }, { name: "D", color: "Green", size: 50 }],
filter = { color: ["Blue", "Black"], size: [70, 50] },
filteredData = filterIt(products, filter);
console.log(filteredData);
.as-console-wrapper { max-height: 100% !important; top: 0; }
答案 1 :(得分:1)
这是另一种选择:
function filterIt(products, filter) {
return products.filter(p => {
for (const k in filter) {
if (filter[k].indexOf(p[k]) === -1) {
return false;
}
}
return true;
})
}
查看Demo
如果要在逻辑中使用“或”而不是“与”,则修改的前一个功能将是:
function filterIt(products, filter) {
return products.filter(p => {
for (const k in filter) {
// if a value of any property of the product is contained in a filter array, include it
if (filter[k].indexOf(p[k]) !== -1) {
return true;
}
}
return false;
})
}
为此也请参阅Demo:)
答案 2 :(得分:0)
const products = [{
name: "A",
color: "Blue",
size: 50
},
{
name: "B",
color: "Blue",
size: 60
},
{
name: "C",
color: "Black",
size: 70
},
{
name: "D",
color: "Green",
size: 50
}
];
const filter = {
color: ["Blue", "Black"],
size: [70, 50]
};
let filterIt = (products, filter) => {
return products.filter(p => {
//get all filter keys
let keys = Object.keys(filter);
let validkeys = [];
keys.forEach(k=>{
// check if filter property exist and includes filter value
if(p.hasOwnProperty(k) && filter[k].includes(p[k])){
validkeys.push(true);
}
})
//check all filter matches
return validkeys.length === keys.length;
});
}
const filteredData = filterIt(products, filter);
console.log("...filteredData", filteredData);