0

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 :

"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

Thank you.

asked May 5, 2022 at 5:58

2 Answers 2

4

You want a flat list of the values from the items inside the English key:

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);

answered May 5, 2022 at 6:03
Sign up to request clarification or add additional context in comments.

5 Comments

Thank you but what if the in the output we only need totalStudents of English. How will we do that then?
@ApoorvaOjha Why did your question not say from the start what you need?
Also, read my code, understand what it does, experiment a little, and you will figure it out. You don't depend on me making it copy-and-paste ready for you.
Although my answer is being accepted, I appreciate this less code flatMap approach
@Andus It's a moot point anyway, as it only solves the problem the OP asked for, not the problem the OP wanted to solve.
0

Assume you have an English array with N objects like below.

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

["33", "98", "2", "35", "99", "3"]
answered May 5, 2022 at 6:05

1 Comment

Instead of .map() followed by .flat() there's the Array.prototype.flatMap()

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.