简体   繁体   中英

Building dynamic json using javascript/angularjs

I am building a dynamic json with the data coming from the server using angularjs. I have declared it as below. it only works if data from server has one item in the object array. How should i declare for it to work dynamically?

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

  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; } } 

This only works if there is one record coming from there server

Use push() method in the for loop to add data into item.

for (var i=0; i<$scope.data.length; i++)
{
   //create a json object from your result.
   let obj = { id: $scope.data[i].id, locations: .....};
   $scope.items.push(obj)
}

you can do like below

 var $scope.items = [];
    for (var i=0; i<$scope.data.length; i++)
    {
        var obj ={};
        obj.id = $scope.data[i].id;
        obj. locations = $scope.data[i].locations;// can assign locations array here.
        $scope.items.push(obj);
    }

The Actual Problem is

$scope.data is already array with data that why you can access index i of it

where as $scope.items is array but still not indexed so Solution is 1. Use Push to add data 2.Firstly create index with json and then add data

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM