javascript - Java Script: loop through JSON -


how loop through provided json every grade years , paste them in array?i'm quite new js explanation welcome. expected array example [2,4,2,5,4,5,4.5,2,3.5,5,5,5,5,5]

{     "first_name": "ala",     "last_name": "kowalski",     "birth_date": "29 aug 1990",     "indeks_number": "9454530",     "year_of_study": "2",     "courses": {         "2013": {             "algorithmsi": {                 "grades": {                     "exercices": [                         2,                         4                     ],                     "lecture": [                         2,                         5                     ]                 }             },             "basicphysicsi": {                 "grades": {                     "exercices": [                         4                     ],                     "lecture": [                         5                     ]                 }             },             "programmingi": {                 "grades": {                     "exercices": [                         4.5                     ],                     "lecture": [                         2,                         3.5                     ]                 }             }         },         "2014": {             "programmingii": {                 "grades": {                     "exercices": [                         5                     ],                     "lecture": [                         5                     ]                 }             },             "basicphysicsii": {                 "grades": {                     "exercices": [                         5                     ],                     "lecture": [                         5                     ]                 }             },             "algorithmsii": {                 "grades": {                     "exercices": [                         5                     ],                     "lecture": [                         5                     ]                 }             }         }     } } 

i might use json.stringify way iterate through object:

grades = []; json.stringify(obj, function(key, value) {     if (key === 'grades')          grades = grades.concat(value.exercices, value.lecture);     return value; }); 

how works

json.stringify designed convert object json string. that, iterates on values in object @ levels. provides ability specify replacer parameter, function called each key/value pair encounters. here, use replacer not control stringification, chance examine each key/value pair see if key 'grades', , if add grades grades array. have return value json.stringify keeps iterating. actual result json.stringify irrelevant , thrown away.


Comments

Popular posts from this blog

ruby on rails - RuntimeError: Circular dependency detected while autoloading constant - ActiveAdmin.register Role -

c++ - OpenMP unpredictable overhead -

javascript - Wordpress slider, not displayed 100% width -