Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

189
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda