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

190
Vistas
How to iterate over array and save data using hooks

Tha idea is iterate over a array and save (or update) values.

const [skills, setSkills] = useState([]);

useEffect(() => {
    Object.entries(array).forEach(([k, v]) => {
       console.log("The skill is: ", k, " and value: ", v)
       setSkills({ ...skills, [k]: v })
    });
}, [array]);

The output is:

The skill is:  1  and value:  30
The skill is:  2  and value:  40
The skill is:  3  and value:  90

That's ok and I assume that "skills" should be:

{1: 30, 2: 40, 3: 90}
   1: 30
   2: 40
   3: 90

but actually, it only saving the last input. I mean, I see the following:

{3: 90}
   3: 90

Please, somebody can explain why? And how to do it the right way? Thanks!!!

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

0

Skills are array of objects at first but you change it to single object in the loop that's why you only see the last output in the state

this should fix your problem

useEffect(() => {
    Object.entries(json_h).forEach(([k, v]) => {
       console.log("The skill is: ", k, " and value: ", v)
       setSkills([ ...skills, {[k]: v} ]) // notice changes here
    });
}, [json_h]);

though I suggest save the new values in a temporary array then change the state once this will get rid of unnecessary setState calls

useEffect(() => {
    let tempArr = [];
    Object.entries(json_h).forEach(([k, v]) => {
       console.log("The skill is: ", k, " and value: ", v)
       tempArr.push({[k]: v})
    });
    setSkills([...skills, ...tempArr])
}, [json_h]);
about 4 years ago · Juan Pablo Isaza Denunciar

0

You can do:

const [skills, setSkills] = useState([])

useEffect(() => {
  setSkills([
    ...skills,
    ...Object.entries(json_h).map(([k, v]) => ({[k]: v})),
  ])
}, [json_h])
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