Skip to content

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:

const [page, setPage] = useState({
        1: false,
        2: false,
        3: false,
        4: true,
        5: false,
        6: false,
        7: false
    });

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.

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:

for (const [key, value] of Object.entries(page)) {
  if (value) {
     console.log(key);
  }
}