【问题标题】:Building dynamic json using javascript/angularjs使用 javascript/angularjs 构建动态 json
【发布时间】:2018-03-12 05:44:16
【问题描述】:

我正在使用来自使用 angularjs 的服务器的数据构建一个动态 json。我已将其声明如下。仅当来自服务器的数据在对象数组中有一项时才有效。我应该如何声明它才能动态工作?

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

这仅在有来自该服务器的一条记录时才有效

【问题讨论】:

  • 检查 - $scope.data.length$scope.items.length
  • 我仍在寻找这个问题的最佳答案。

标签: javascript arrays angularjs json ecmascript-5


【解决方案1】:

在for循环中使用push()方法将数据添加到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)
}

【讨论】:

    【解决方案2】:

    你可以像下面那样做

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

    【讨论】:

      【解决方案3】:

      实际问题是

      $scope.data 已经是包含数据的数组,您可以访问它的索引 i

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

      【讨论】:

      • 您能否提供示例代码作为如何实现它?
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-05-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多