'How to return all objects in an array of objects?
I am trying to get all objects in an array of objects. I've tried searching online for a solution and got some helpful tips. However, it only returns one of the objects and not all of the objects in the array. I can't seem to figure out why?
Array of objects:
[{"id":"_f939IxLRjn0YVvOEg5SR","type":"multiple","category":"Entertainment: Video Games","question":"Which Sonic the Hedgehog game was originally supposed to be packaged with Sonic 3, but was cut in half due to time constraints?","correct_answer":"Sonic & Knuckles","incorrect_answers":["Sonic 2","Sonic CD","Sonic 3D Blast"]},{"id":"84LQQOeMZqeqYweGXKZ47","type":"multiple","category":"General Knowledge","question":"Which American-owned brewery led the country in sales by volume in 2015?","correct_answer":"D. G. Yuengling and Son, Inc","incorrect_answers":["Anheuser Busch","Boston Beer Company","Miller Coors"]}]
Array.reduce code:
const [quizObj, setQuizObj] = useState({});
useEffect(() => {
setQuizObj(() => {
return allQuiz.reduce((obj, item) => Object.assign(obj, { ...item }), {});
});
}, [allQuiz]);
console.log output:
{"id":"84LQQOeMZqeqYweGXKZ47","type":"multiple","category":"General Knowledge","question":"Which American-owned brewery led the country in sales by volume in 2015?","correct_answer":"D. G. Yuengling and Son, Inc","incorrect_answers":["Anheuser Busch","Boston Beer Company","Miller Coors"]}
Desired output:
{item: {"id":"_f939IxLRjn0YVvOEg5SR","type":"multiple","category":"Entertainment: Video Games","question":"Which Sonic the Hedgehog game was originally supposed to be packaged with Sonic 3, but was cut in half due to time constraints?","correct_answer":"Sonic & Knuckles","incorrect_answers":["Sonic 2","Sonic CD","Sonic 3D Blast"]}, {"id":"84LQQOeMZqeqYweGXKZ47","type":"multiple","category":"General Knowledge","question":"Which American-owned brewery led the country in sales by volume in 2015?","correct_answer":"D. G. Yuengling and Son, Inc","incorrect_answers":["Anheuser Busch","Boston Beer Company","Miller Coors"]}}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
