Mukund Gandlur Mukund Gandlur - 7 months ago 15
Javascript Question

JavaScript Retrieving data from a JSON

I have a JSON which looks like this.

{
"class_details":{
"class_1":{student_4":"<name>","student_3":"<name>,student_2":"<name>","student_1":"<name>},
"class_2":{"student_1":"<name>},
"class_0":{student_2":"<name>","student_1":"<name>
}
}


I am trying to use a loop to iterate over the classes but I am not able find a perfect way to do it.

I cant do something like this,

for(int i=0; i < $scope.rounds.class_details.length;i++)
console.log($scope.rounds.class_details.round_[i])


So i am doing this

for(int i=0; i < $scope.rounds.class_details.length;i++)
console.log(Object.keys($scope.rounds.class_details)[i])


But here the class details do not come in an order and this matters in my case.

It would be great if there is an alternative similar to

for(int i=0; i < $scope.rounds.class_details.length;i++)
console.log($scope.rounds.class_details.round_[i])


or if there is a simple way to sort the JSON class details.

Answer

The simplest way to read data like you're hoping is the following:-

 for(int i=0; i < $scope.rounds.class_details.length;i++)
    console.log($scope.rounds.class_details["round_" + i]);

This is because you can access an objects property in two ways: -

  1. Allows you to pass a dynamic value in (i.e. the i value)

    object["property" + withVariable + "Name"]

  2. Simple, readable way where you know the property.

    object.propertyName