[SOLVED] Why I can not loop through object in react-typescript

Issue

I can not loop throught object in react with typescript. I am using redux toolkit and I want to get chosenFilters arrays.

const chosenFilters = useSelector((state: RootState) => state.recipe.filters);
  for (const chosenFilterArray of chosenFilters) {
    console.log(chosenFilterArray);
  }


error: 

Type 'filters' is not an array type or a string type.


interface: 

export interface filters {
  filterTypes: string[];
  filterLengths: string[];
}

Solution

You can’t iterate over an object with a for/of. But you can use Object.valus(someObj) to get the values from that object as an array and iterate over that.

for (const chosenFilterArray of Object.values(chosenFilters)) {
  console.log(chosenFilterArray);
}

Answered By – Alex Wayne

Answer Checked By – Dawn Plyler (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *