简体   繁体   English

使用javascript / angularjs构建动态json

[英]Building dynamic json using javascript/angularjs

I am building a dynamic json with the data coming from the server using angularjs. 我正在使用来自使用angularjs的服务器中的数据构建动态json。 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循环中使用push()方法将数据添加到项目中。

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 $ scope.data已经是带有数据的数组,因此您可以访问它的索引i

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是数组,但仍未索引,因此解决方案是1.使用Push添加数据2.首先使用json创建索引,然后添加数据

$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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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