HUKS HUKS - 2 months ago 8
JSON Question

How to create certain number of JSON object using AngularJS

I have this JSON object like below.

$scope.members =
[{
id: "member_0",
json: {
name: $cookieStore.get("member_0_name"),
class: $cookieStore.get("member_0_class"),
items: {
fooItem: $cookieStore.get("member_0_items_fooItem")
}
}
},
{
id: "member_1",
json: {
name: $cookieStore.get("member_1_name"),
class: $cookieStore.get("member_1_class"),
items: {
fooItem: $cookieStore.get("member_1_items_fooItem")
}
}
}];


Now, I would like to improve the code so the certain number of JSON object can be created with the given number. I expect the code look would like below in pseudo but was unable to work it out.

var num_of_members = 5;

for (var i = 0; i < num_of_members; i++) {
$scope.members =
[{
id: "member_"+[i],
json: {
name: $cookieStore.get("member_"+[i]+"_name"),
class: $cookieStore.get("member_"+[i]+"_class"),
items: {
fooItem: $cookieStore.get("member_"+[i]+"_items_fooItem")
}
}
}];
}

Answer

i think this code will helps you:

var num_of_members = 5;
$scope.members = [];

for (var i = 0; i < num_of_members; i++) {
  var member = {
    id: "member_"+[i],
    json: {
      name: $cookieStore.get("member_"+[i]+"name"),
      class: $cookieStore.get("member_"+[i]+"class"),
      items: {
        fooItem: $cookieStore.get("member_"+[i]+"_items_fooItem")
      }
    }
  };
  $scope.members.push(member); 
}

Just create a new member for each id and push it into the array of members.