Skip to content
Advertisement

React JS useState get key where value is true

simple question here. How can I find a key in the state where the value is true? For instance. Lets say I have this set as state:

JavaScript

How can I return the key where the value is true? in this case 4?

I would also like to return the length of the key / value pairs (7) and even be able to loop though the key / value pairs but that isn’t as important as my main question.

Hope you can help. Thanks.

Advertisement

Answer

You can iterate through an object using

  • Object.keys(myObject) that will return all keys.
  • Object.values(myObject) that will return all values.
  • Object.entries(myObject) that will return all keys and values.

Should look like this:

JavaScript
Advertisement