Reputation: 869
I have an object 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.
Upvotes: 0
Views: 54
Reputation: 18642
To get the keys in ascending order do:
var class_details_keys = Object.keys($scope.rounds.class_details);
class_details_keys = class_details_keys.sort(function(a,b) {return (+a.substring(6)) - (+b.substring(6));});
for(int i=0, length = class_details_keys ; i < length;i++)
console.log($scope.rounds.class_details[class_details_keys[i]]);
This will return your classes in ascending order by taking the substring after 'class_' and ordering them. You can't do a simple string comparison since "4" > "10" will return incorrect result.
Upvotes: 1
Reputation: 591
First, fix json. NOTE: there are some quotes missing in the original code.
"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>"
}
}
Followed to this:
//parse to json. Assume the
//'body' is the json data received
//if there is data in body
if(body){
//parse body
var parsed_body= JSON.parse(body);
//your data
var class_details = parsed_body.class_details;
var class_2_student_1 = parsed_body.class_details.class_2.student_1;
//if you want to print json directly to the front-end,
//then Object Object may be printed out. to prevent this,
//one could use .toString() to convert Object to String.
}
else{}//do something if no data in the body
Upvotes: 0
Reputation: 1286
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: -
Allows you to pass a dynamic value in (i.e. the i value)
object["property" + withVariable + "Name"]
Simple, readable way where you know the property.
object.propertyName
Upvotes: 0