sai123
sai123

Reputation: 105

How to build a dynamic json object array using angularjs?

I have declared it as below and also showing data is actually coming from the server but the following code doesn't work if there are multiple arrays in the data coming from the server.

$scope.items = [
{
  id: “”,
  locations: [{
     name: “”
  }]
}
]

Data from server looks this way.

  $scope.data = [
  {
    id: '1',
    type: 'a1',
    year: '1999',
    locations: [
      {id:'1', name: 'abc'},
      {id:'11', name: 'xyz'}]
  },
  {
    id: '11',
    type: 'a2',
    year: '2000',
    locations: [
    {id:'22', name: 'abc1'},
    {id:'23', name: 'xyz1'},
    {id:'24', name: 'efg1'}]
  }
...
]

 for (var i=0; i<$scope.data.length; i++)
    {
    	$scope.items[i].id = $scope.data[i].id;
        for(var j=0; j<$scope.data[i].locations.length; j++) {
             $scope.items[i].locations[j].name = $scope.data[i].locations[j].name;
        }
    }

Upvotes: 0

Views: 368

Answers (1)

AmitKhiwal
AmitKhiwal

Reputation: 59

I have done something like this earlier.

I created a function which would return a json object which in your case would be like

$scope.getJson = function(){
     return { 
         id: “”,
         locations: []
     }
}

Now you have to modify your loop a little bit to handle multiple JSONArray elements like

 for (var i=0; i<$scope.data.length; i++){
     var temp = $scope.getJson();
     temp.id = $scope.data[i].id;
     temp.locations = $scope.data[i].locations;
        
     $scope.items.push(temp);
 }

If you want to copy some specific properties from $scope.data[i].locations only, then you can use another loop else you can assign the locations array directly.

Upvotes: 1

Related Questions