简体   繁体   English

如何在Javascript中循环一个arrays的object?

[英]How to loop through an object of arrays in Javascript?

For the below code,对于下面的代码,

const groupbysubject = {
                    "Mathematics":
                    [
                      {totalStudents: "23", average: "78", class: "2"},
                      {totalStudents: "25", average: "80", class: "3"}
                    ],
                    "English":
                    [
                      {totalStudents: "33", average: "98", class: "2"},
                      {totalStudents: "35", average: "99", class: "3"}
                    ],
                    "Science":
                    [
                      {totalStudents: "43", average: "65", class: "2"},
                    ]
                  }

                

var isEnglishPresent = Object.fromEntries(
                           Object.entries(groupbysubject).filter(
                             ([key, val])=> key.includes("English")
                            )
                        );

I want the following output:我想要以下 output:

"33" "98" "2" "35" "99" "3" “33” “98” “2” “35” “99” “3”

I have filtered the above groupbysubject object into isEnglishPresent object. How do I proceed further to iterate over isEnglishPresent and get the above output. Please help我已经将上面的groupbysubject object过滤成isEnglishPresent object。我如何进一步迭代isEnglishPresent并得到上面的output。请帮助

Thank you.谢谢你。

You want a flat list of the values from the items inside the English key:您需要English键内的项目的平面列表:

 const groupbysubject = { "Mathematics": [ {totalStudents: "23", average: "78", class: "2"}, {totalStudents: "25", average: "80", class: "3"} ], "English": [ {totalStudents: "33", average: "98", class: "2"}, {totalStudents: "35", average: "99", class: "3"} ], "Science": [ {totalStudents: "43", average: "65", class: "2"}, ] }; var englishData = groupbysubject.English.flatMap(item => Object.values(item)); console.log(englishData);

Assume you have an English array with N objects like below.假设您有一个包含 N 个对象的英语数组,如下所示。

const English = [
  {totalStudents: "33", average: "98", class: "2"},
  {totalStudents: "35", average: "99", class: "3"},
  ...
]

Here's how you extract all the values and put it into an array.以下是提取所有值并将其放入数组的方法。

English.map(item => Object.values(item)).flat()

Here's the output这是 output

["33", "98", "2", "35", "99", "3"]

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

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