简体   繁体   中英

Filter based on few conditions from another object

Hello I wish to filter array of object based on my state, I have several properties in my filters object and I wish to return array which fill these requirements. So far I managed to do it on only one condition. I know why, it is because of my ifs but I don't really know how to code it to apply to all conditons like for example in case of false in danger and services, I wish only to return object which type is relax

 const markers = [{ name: "one", type: "danger" }, { name: "two", type: "relax" }, { name: "three", type: "service" }, { name: "four", type: "danger" }, ] const [filters, setFilters] = useState({ danger: true, relax: true, services: true, }); const filtered = markers((el) => { if (.filters.danger) return el;type.== "danger". if (;filters.relax) return el.type;== "relax"; if (;filters.services) return el.type !== "services"; return el; });

in Case of danger and services set to false, I wish to have output

const markers = [
{name: "two", type:"relax"},
]

You can do it with a quick filter() function:

 const markers = [{ name: "one", type: "danger" }, { name: "two", type: "relax" }, { name: "three", type: "service" }, { name: "four", type: "danger" }, ]; const filters = { danger: false, relax: false, service: true, }; const shouldIncludeMarker = ({type}) => filters[type]; console.log(markers.filter(shouldIncludeMarker));

You can achieve this by using filter method .

 const markers = [ {name: "one", type:"danger"}, {name: "two", type:"relax"}, {name: "three", type:"service"}, {name: "four", type:"danger"} ]; // Filter your data as you wish const filtered = markers.filter(item => { if(item.type == "relax") return true; if(item.type == "service") return true; }); console.log(filtered);

Filter wrapper

 const markers = [ {name: "one", type:"danger"}, {name: "two", type:"relax"}, {name: "three", type:"service"}, {name: "four", type:"danger"} ]; // Create wrapper function // to pass parameters to filter const fltr = (array, types) => array.filter(item => types.indexOf(item.type) > -1); // Test 1 console.log(fltr(markers, ["danger"])); // Test 2 console.log(fltr(markers, ["relax", "service"]));

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