This is my Array of objects. I want to filter the objects by passing query in a function.
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
}
];
My desired output which will filter from the query which I am passing in function which can be anything
{
name: "A",
color: "Blue",
size: 50
}, {
name: "C",
color: "Black",
size: 70
}
This is my query object which I will pass to function
const filter = {
color: ["Blue", "Black"],
size: [70, 50]
};
This is my function which I can assign to other variable and use it for further operations
const filteredData = filterIt(products, filter);
You could get the entries of the filter object and take key and value for checking with 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; }
Here is another option:
function filterIt(products, filter) {
return products.filter(p => {
for (const k in filter) {
if (filter[k].indexOf(p[k]) === -1) {
return false;
}
}
return true;
})
}
See a Demo
If you want to make an OR instead of an AND in the logic the previous function modified would be:
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;
})
}
See a Demo for this one too :)
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);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.