在现有json对象中添加新键(数组)

时间:2020-12-17 23:14:37

I've got an array with objects. I need for each object to add a key, which will be an array of other objects.

我有一个带对象的数组。我需要为每个对象添加一个键,它将是一个其他对象的数组。

So my code looks like this:

所以我的代码看起来像这样:

$scope.array = [];

$http.get(url).success(function(data) {

   $scope.array = data;

   // Now my array has some objects
   var i = 0;
   function() getSomeData(i) { 
      if(i<array[i].length()) {
         $http.get(url + array[i].someKey).success(function(data){
            $scope.array[i].push(data);
            i++;
            getSomeData(i);
         })
      } 
   }

})

getSomeData(0);

But I am getting Error:array.push is not a function

但我收到错误:array.push不是一个函数

Why's that happening ?

为什么会这样?

2 个解决方案

#1


5  

You are trying to push to an object instead of the array. Either do:

您正在尝试推送到对象而不是数组。要么:

$scope.array.push(data) to add a new object.

$ scope.array.push(data)添加一个新对象。

or do $scope.array[i] = data to update the object at the specific index in the array.

或者$ scope.array [i] =数据来更新数组中特定索引处的对象。

#2


0  

Objects in JSON are added using below two techniques. You can try one of them.

使用以下两种技术添加JSON中的对象。你可以尝试其中一个。

object["property"] = value;

or

要么

object.property = value;

#1


5  

You are trying to push to an object instead of the array. Either do:

您正在尝试推送到对象而不是数组。要么:

$scope.array.push(data) to add a new object.

$ scope.array.push(data)添加一个新对象。

or do $scope.array[i] = data to update the object at the specific index in the array.

或者$ scope.array [i] =数据来更新数组中特定索引处的对象。

#2


0  

Objects in JSON are added using below two techniques. You can try one of them.

使用以下两种技术添加JSON中的对象。你可以尝试其中一个。

object["property"] = value;

or

要么

object.property = value;