0

I currently have this JSON file

{   
"name": "Connor Atherton",
"course": "Combined Sciences",

"modules" : {

    "MATH210": 
    {
        "weekly": 65,
        "weekly2": 76,
        "exam": 80
    },

    "MATH215": {
        "weekly": 65,
        "exam": 80
    },

    "MATH220": {
        "weekly": 65,
        "exam": 80
    },

    "MATH225": {
        "weekly": 65,
        "weekly2": 98,
        "exam": 80
    },

    "SCC210": {
        "weekly": 65,
        "exam": 80
    },

    "SCC204": {
        "weekly": 65,
        "exam": 80
    }

}

}

As you can see in each module there could be a different number of properties which will be retrieved dynamically.

I am currently looping over each module like this

$.each(json.modules, function(i, item) {
    console.log(i + " " + item.exam);
});

However this won't work for all the modules since they can all have a different number of properties.

I have been trying to loop over each module's properties with for loops but I can't quite get it to work. I figured I should use

item.length

somewhere in the loop but I'm not sure.

Do you have any idea how I could loop over each module if each one has a different number of properties?

Thanks

1 Answer 1

3

If I understood you correctly:

$.each(json.modules, function(i, item) {
    for (var key in item){
        // output, to example: "exam = 80"
        console.log(key + ' = ' + item[key]);
    }
});
Sign up to request clarification or add additional context in comments.

1 Comment

Yeah that did it thanks, I had var item in i instead of key in item!

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.