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

286
Visualizações
Javascript - How to use reduce to create a new object with properties?

I want to convert an array into an object and assign properties. I tried using the reduce method, but I am doing it by only returning one value in the array.

How can I get all values in the array and place them into my custom property in the new object?

Initial array:

["Cow Bell","Bass Drum","Maraca"]

Reduce code:

const [formData, setFormData] = useState({});

setFormData(() => {
  return props.incorrect_answers.reduce(
    (a, v) => ({ ...a, option: v }),
    {}
  );
});

Output:

{"option":"Maraca"} // Only outputs one value

If I use this reduce code, it returns all values but with properties with the same name:

setFormData(() => {
  return props.incorrect_answers.reduce(
    (a, v) => ({ ...a, [v]: v }),
    {}
  );
});

Output:

{"Cow Bell":"Cow Bell", "Bass Drum": "Bass Drum", "Maraca":"Maraca"} // Outputs all values but with the same property name

Desired output I am looking for:

{"option":"Cow Bell", "option":"Bass Drum", "option":"Maraca"}
about 4 years ago · Juan Pablo Isaza
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