将空数组添加到 Angular 中的 json 对象

Adding empty array to json object in Angular

本文关键字:中的 json 对象 Angular 数组 添加      更新时间:2023-09-26

问题问题:我正在调用 API,它返回对象。现在我想将空数组添加到此对象并在我的视图中使用它。我如何使用角度实现这一点?

控制器 这是手动

工作的
$scope.deliveryData = [
            {
                productName: 'ProductA ProductA ProductA', quantity: '20', deliveries: []
            },
            {
                productName: 'Product B', quantity: '10', deliveries: []
            }
        ];

控制器 这不起作用:(我将如何添加(交付:[])到此?

 $scope.deliveryData; // This will be now populated from API 
     MyService.delivery()
        .success(function(data){
            $scope.deliveryData= data;
            console.log(data) //this data does not contain the empty array, how i append to it?
        })
        .error(function(status,data){
            console.log(status);
            console.log(data);
        })

我不知道如何在角度中实现这一目标,甚至我不知道我这样做是否正确。请给我任何建议。

更新 1

 .success(function(data){
                $scope.deliveryData = data;
                console.log("Before Change");
                console.log($scope.deliveryData);
                for (var i = 0; i < $scope.deliveryData.length; i++) {
                    $scope.deliveryData[i].deliveries = [];
                }
                console.log("After Change");
                console.log($scope.deliveryData);
            })

来自 API 的数据格式如下:

-Object {delivery: Array[1]}
 --delivery: Array[1]
   ---0:Object
   ----name: "ProductA ProductA ProductA"
   ----quantity: 14 

要向每个产品项添加{deliveries: []},您应该执行以下操作:

    .success(function(data){
        $scope.deliveryData = data.delivery;
        for (var i = 0; i < $scope.deliveryData.length; i++) {
            $scope.deliveryData[i].deliveries = [];
        }
    })

更新

这是基本的东西,不可能不起作用,请在此处查看:

var $scope = {};
$scope.deliveryData = [ // no deliveries here
    {productName: 'ProductA ProductA ProductA', quantity: '20'},
    {productName: 'Product B', quantity: '10'}
];
for (var i = 0; i < $scope.deliveryData.length; i++) {
    $scope.deliveryData[i].deliveries = [];
}
document.getElementsByTagName('pre')[0].innerHTML = JSON.stringify($scope, null, ''t');
<pre></pre>