繁体   English   中英

如何返回对象数组中的所有对象?

[英]How to return all objects in an 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 代码:

const [quizObj, setQuizObj] = useState({});

useEffect(() => {
    setQuizObj(() => {
      return allQuiz.reduce((obj, item) => Object.assign(obj, { ...item }), {});
    });
  }, [allQuiz]);

控制台日志 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"]}

所需的 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"]}} 

如果您试图将对象数组转换为单个 object,那么应该有一种方法可以使用 output object 中的唯一键来标识每个数组项。

假设:每个数组项都有一个id属性,并且每个项的id都是唯一的。 如果id不唯一,则数据可能会被覆盖。

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

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

我有意使用.forEach而不是.reduce因为它更容易阅读。 但是您当然可以坚持使用.reduce来获得相同的结果。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM