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

293
Vistas
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 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