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"}