0

How would you loop through provided JSON to get every grade from all the years and paste them in array?I'm quite new to JS so any explanation is welcome. Expected array for this example would be [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
                    ]
                }
            }
        }
    }
}
1
  • 1
    so you can simple use for...in and for loop Commented Dec 2, 2014 at 7:20

4 Answers 4

2

I might use JSON.stringify as a way to iterate through the object:

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

How this works

JSON.stringify is designed to convert an object into a JSON string. To do that, it iterates over all values in the object at all levels. It also provides the ability to specify a replacer parameter, which is a function called with each key/value pair it encounters. Here, we use the replacer not to control the stringification, but to get a chance to examine each key/value pair to see if the key is 'grades', and if so add those grades to the grades array. We have to return value so that JSON.stringify keeps iterating. The actual result from JSON.stringify is irrelevant and thrown away.

Sign up to request clarification or add additional context in comments.

1 Comment

Upvoted! This is such a fun, whimsical answer (and I today I learned that stringify accepts a replacer argument). I don't know if I personally would use this to iterate an object (stringify is slow enough as it is), but it definitely illustrates the ease of doing something in JS many different ways ;)
0

Hi you can try this one.

function looop(jsonob) {
    var gradeArray = [];
    for (years in jsonob.courses) {
        for (lessons in jsonob.courses[years]) {
            for (x in jsonob.courses[years][lessons].grades.exercices) {
                gradeArray.push(jsonob.courses[years][lessons].grades.exercices[x]);
            }
            for (x in jsonob.courses[years][lessons].grades.lecture) {
                gradeArray.push(jsonob.courses[years][lessons].grades.lecture[x]);
            }
        }
    }
    return gradeArray;
}

Comments

0
var grades = [];
var obj = <your Object>;

processObj(obj);

function processObj(obj) {
    for (var n in obj) {
        if (n=='exercices' || n=='lectures') {
            for (var j=0;j<obj[n].length;j++) {
                grades.push(obj[n][j]);
            }
        } else {
            processObj(obj[n]);
        }
     }
}

Comments

0

Recursive:

function each(object, iterator) {
    Object.keys(object).forEach(function (key) {
        var value = object[key];
        iterator(value, key);
    });
}

function inArray(array, value) {
    return array.indexOf(value) > -1;
}

function isPlainObject(value) {
    return !!value && typeof value === 'object' && value.constructor === Object;
}

function getGrades(data) {
    var grades = [];
    each(data, function (value, key) {
        if (inArray(['exercices', 'lecture'], key)) {
            grades = grades.concat(value);
        } else if (isPlainObject(value)) {
            grades = grades.concat(getGrades(value));
        }
    });
    return grades;
}

You can test this in Node.js with:

var assert = require('assert');
assert.deepEqual(getGrades(fixture),
                 [2, 4, 2, 5, 4, 5, 4.5, 2, 3.5, 5, 5, 5, 5, 5, 5]);

Where fixture is your JSON.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.