Home > other >  how to filter results of an array of objects
how to filter results of an array of objects

Time:07-13

I am building an app where I have to use a filter on array of objects , so depending of options selected by user I should display results (if there is) matching his query , my array looks like :

const fbdata =  [{"plage": 0, "camping": 0,  
"city": 1, "car": 1,  
 "price": 100, "wifi":  "Yes"}, 
 {"plage": 1, "camping": 0,  
"city": 1, "car": 1,  
 "price": 200, "wifi":  "Yes"}, 
 {"plage": 0, "camping": 0,  
"city": 1, "car": 0,  
 "price": 300, "wifi":  "No"}]

I am storing options that have selected from filter form in object let 's say this is the filter :

 const myfilter ={
    wifi: "Yes",
    price: [90, 150],
    car: 1,
    
  }

so now I should filter my array and bring data matching the query of user here is how I did it and its not working cause its displaying all data , and also I can't figure out to filter price when it is an array or a range of two values:

 let data2= new Set() ;
      let mes2= 'mes2' ;
      dd = fbdata.filter((item) =>{

        for (var key in myfilter) {
          if(myfilter[key] !== undefined){
            
             if (item[key] !== undefined && item[key] == myfilter[key]){
                return data2.add(item)
            }
          
          }
        
      }
return data2

CodePudding user response:

You can use filter

const result = fbdata.filter(
    ({wifi, price, car}) =>
      wifi === myfilter.wifi &&
      car === myfilter.car &&
      price >= myfilter.price[0] &&
      price <= myfilter.price[1]
);

CodePudding user response:

const fbdata =  [
    {"plage": 0, "camping": 0, "city": 1, "car": 1, "price": 100, "wifi":  "Yes"}, 
    {"plage": 1, "camping": 0, "city": 1, "car": 1, "price": 200, "wifi":  "Yes"}, 
    {"plage": 0, "camping": 0, "city": 1, "car": 0, "price": 300, "wifi":  "No"}
]


const myfilter = {
    wifi: "Yes",
    price: [90, 150],
    car: 1,
}

const filterData = (data, filter) => data.filter(x => (x.wifi === filter.wifi &&
                                             x.car === filter.car
                                             && (filter.price[0] < x.price && filter.price[1] < x.price)));

console.log(filterData(fbdata, myfilter));
  • Related