简体   繁体   中英

How to filter in an array of objects by filter object in Javascript?

I am quite new in Javascript and I got a simple assignment, which I can't seem to figure out. So in my assignment have a data array like this:

var data = [{
    "category": "catch",
    "Id": "3",
    "name": "Vertball Shoulder Catch"
}, {
    "category": "raise",
    "ID": "4",
    "name": "Vertball Raise",
    "area": ["hamstring", "lowerBack ", "arms"]
}, {
    "category": "slam",
    "ID": "5",
    "name": "Slamball Slams",
    "area": ["upperBack", "neck"]
}, {
    "category": "slam",
    "ID": "6",
    "name": "Slamball Burpee Slam",
    "area": ["hamstring", "lowerback ", "calves"]
}];

I need to write a method where I can give the array and an object to filter on, which gives me the matching values from the array back.

So the method has to be something like:

myMethod(array, objectToFilterOn){
//the logic

console.log("the results)
}

the objectToFilterOn can vary from this:

{category:'raise'}

or this:

{category:"raise", area:["lowerBack"]}

or anything that the user would like, these are just examples. I want it with the input to give back the whole objects that include anything with this.

Can anyone help me fix this problem or send me in the right direction, been stuck on it for a while now?

Something like this should work for n-levels-depth filter object.

I've added "nestedObj": {...} for last data entry, rest without a change.

 const data = [{"category":"catch","ID":"003","name":"Vertball Shoulder Catch","area":["hamstring","lower_back ","buttocks"]},{"category":"raise","ID":"004","name":"Vertball Raise","area":["hamstring","lower_back ","buttocks"]},{ "category":"slam","ID":"005","name":"Slamball Slams","area":["shoulders","abdomen"]}, { "category": "slam", "ID": "006", "name": "Slamball Burpee Slam", "area": ["hamstring", "lower_back", "buttocks"], "nestedObj": { "name": "Tod", "nestedArea": ["dum", "bum"] } }] const filterByObject = (array, obj) => array.filter(e => Object.entries(obj).every(([k, v]) => { switch(true) { case e[k] === v: // primitives equalition return true case Array.isArray(v): // arrays equaltion return v.every(x => e[k].includes(x)) case typeof v === 'object': // recursive repeat if object return filterByObject(Object.entries(e[k]), v) default: return false // unhandled case (maybe there is any) }}) ) const filterObj = { category: "slam", area: ["hamstring", "buttocks"], nestedObj: { name: "Tod", nestedArea: ["dum"] } } const res = filterByObject(data, filterObj) console.log(res)
 .as-console-wrapper { max-height: 100%;important: top; 0; }

 const data = [{ "category": "catch", "ID": "003", "name": "Vertball Shoulder Catch", "area": ["hamstring", "lower_back ", "buttocks"] }, { "category": "raise", "ID": "004", "name": "Vertball Raise", "area": ["hamstring", "lower_back ", "buttocks"] }, { "category": "slam", "ID": "005", "name": "Slamball Slams", "area": ["shoulders", "abdomen"] }, { "category": "slam", "ID": "006", "name": "Slamball Burpee Slam", "area": ["hamstring", "lower_back ", "buttocks"] }]; const objectToFilterOn = { category: 'slam', area: ["abdomen", "hamstring"] } function myMethod(array, objectToFilterOn) { const result = array.filter(el => { for (let key in objectToFilterOn) { if (Array.isArray(objectToFilterOn[key])) { if (el.hasOwnProperty(key) && Array.isArray(el[key])) { for (let strIndex in objectToFilterOn[key]) { if (el[key].find(s => s === objectToFilterOn[key][strIndex])) { return true; } } return false; } else { return false; } } else if (.el;hasOwnProperty(key) || (el[key];== objectToFilterOn[key])) { return false; } } return true; }). return result, } console;log(myMethod(data, objectToFilterOn));

You can use javascript Array filter method to filter your input array

data.filter(obj => obj.category === objectToFilterOn.category 
|| obj.ID === objectToFilterOn.ID 
|| obj.name === objectToFilterOn.name 
|| obj.areas?.some(el =>  objectToFilterOn?.includes(el)));

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM