Home > Software design >  JavaScript Objects filtering out specific property names
JavaScript Objects filtering out specific property names

Time:07-28

I am creating a filter for a diagram. Whenever a filter is clicked it should remove that category from the diagram. The api call returns an object with names. let’s say the object returns 40 items and I want to filter 5 out by name. What is the best way to approach this?.

I tried to manually type the property names into an array and run the .filter on my object like below. However it returns the entire object unfiltered.

filterDiagram() {

    Const array = [“all the names of the properties I want to filter out”]
    
    carbonates = array.forEach(x) => {console.log(x)}
    
    Const filterCat = data.filter (io => 
    io.name !== carbonates)

}

CodePudding user response:

Let's say, the array consists of all the names/categories you want to take out.

const toBetakenOut = ['fruits','salts', 'etc' ] 
// Please make sure they are not 1 string but rather comma-separated values.

You can filter the API data by using the filter function on the data,to remove objects with names that are within toBetakenOut.

 const filterCat = data.filter (io => !toBetakenOut.includes(io.name))

CodePudding user response:

function filterDiagram(){
   const dontWantsArray = [/*all of the things you dont want*/];

   // Outputs an array of keys
   const filteredKeys = Object.keys(yourJSObject)
                              .filter(key => !dontWantsArray.includes(key));

   // After you found the keys you can get the values to another array by keys
   const filteredValues = filteredKeys.map(key => yourJSObject[key]);
}
  • Related