Home > Net >  How to return all objects in an array of objects?
How to return all objects in an array of objects?

Time:02-25

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

CodePudding user response:

If you're trying to transform an array of objects into a single object, then there should be a way to identify each array item with a unique key in the output object.

Assumption: every array item has an id property and each items id is unique. If the ids aren't unique, the data might be overwritten.

useEffect(() => {
    const combinedObj = {};

    allQuiz.forEach((obj) => {
      combinedObj[obj.id] = { ...obj };
    });
  
    return combinedObj; 
});

I have intentionally used .forEach instead of .reduce as it's easier to read. But you can of course stick to .reduce to achieve the same result.

  • Related