Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

294
Views
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
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!