Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save emfluenceindia/0ec4d94153c4b5ca2d4cb6b64fb31b89 to your computer and use it in GitHub Desktop.
Save emfluenceindia/0ec4d94153c4b5ca2d4cb6b64fb31b89 to your computer and use it in GitHub Desktop.
ES6 - Simple example of how to use Object.keys and Array.map in a complex JavaScript object
/**
The following example is a simple use case of Object.keys and Array.map functions
to loop through a nested JavScript array with object nested into it.
Steps:
1. Used a map() method on the main array, i.e. examResult
2. Started looping through the mapped object
3. If the loop encounters a JavaScript Object (marks in this case) it applied Object.keys method on it
Structure of examResult array:
examResut[ // JS Array
student: { // Individual Array item as JS Object
...
marks: // JS Object
{
...
}
},
...
]
*/
const examResult = [ // JS array
{
student: {
name: 'Gordon Smith',
roll: 54,
class: 'VII',
marks: { // The inner object
maths: 93,
chemistry: 91,
physics: 89,
biology: 96,
geography: 91
},
fullMarks: 500,
marksObtained: 460,
percentage: 92,
grade: 'A+'
}
},
{
student: {
name: 'Rebecca Hall',
roll: 39,
class: 'VII',
marks: {
maths: 95,
chemistry: 92,
physics: 84,
biology: 90,
geography: 89
},
fullMarks: 500,
marksObtained: 450,
percentage: 90,
grade: 'A+'
}
}
];
examResult.map( student => { // First we apply a map() method since the input is an array, examResult = [...]
const st = student;
Object.keys(st).forEach( result => {
const objResult = st[result];
Object.keys(objResult).forEach( key => {
if('object' === typeof(objResult[key])) { // Checking if there is a JS object (in this cas we have one, which is 'marks')
Object.keys( objResult[key] ).forEach( subject => { // We encounter a JS object 'marks' and hence apply Object.keys method
const subjectName = subject.charAt(0).toUpperCase() + subject.slice(1); // Formatting purppose only to make first letter capital.
// Outputting using ES6 template literals rather than using conventional string concatenation
console.log( `${subjectName}: ${objResult[key][subject]}` );
} );
}
else {
const itemName = key.charAt(0).toUpperCase() + key.slice(1); // Formatting purppose only to make first letter capital.
// Outputting using ES6 template literals rather than using conventional string concatenation
console.log( `${itemName}: ${objResult[key]}` );
}
});
});
console.log('***************************************');
} );
/**
Output:
Name: Gordon Smith
Roll: 54
Class: VII
Maths: 93
Chemistry: 91
Physics: 89
Biology: 96
Geography: 91
FullMarks: 500
MarksObtained: 460
Percentage: 92
Grade: A+
***************************************
Name: Rebecca Hall
Roll: 39
Class: VII
Maths: 95
Chemistry: 92
Physics: 84
Biology: 90
Geography: 89
FullMarks: 500
MarksObtained: 450
Percentage: 90
Grade: A+
***************************************
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment