Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

162
Vistas
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.

about 4 years ago · Juan Pablo Isaza
3 Respuestas
Responde la pregunta

0

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);
  }
}
about 4 years ago · Juan Pablo Isaza Denunciar

0

You can use Object.entries() to get an array of [key, value] pairs, and then you can use all relevant array methods/properties:

const page = {
  1: false,
  2: false,
  3: false,
  4: true,
  5: false,
  6: false,
  7: false
}

const entries = Object.entries(page)

console.log({ firstTrue: entries.find(([, v]) => v)?.[0] })

console.log({ numberOfKeys: entries.length })

However, it would be easier just to store the state as an array:

const page = [false, false, false, true, false, false, false]

console.log({ firstTrueIndex: page.findIndex(v => v) })

console.log({ numberOfItems: page.length })

about 4 years ago · Juan Pablo Isaza Denunciar

0

Try this :

const [page, setPage] = useState({
        1: false,
        2: false,
        3: false,
        4: true,
        5: false,
        6: false,
        7: false
    });
    let trueValue=[];
    for (let i in page)
    {
      if (page[i] === true)
      trueValue.push(i);
    }
    console.log(trueValue);

This code will iterate the object and gives the key when the value is true.

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda