2013-07-16 105 views
0

我有這樣一個JSON對象,所以:循環到JSON值添加到陣列

$scope.object = { 
    'thing1': { 
     'content': 'blah blah', 
     'order': '1', 
}, 
    'thing2': { 
     'content': 'blah blah blah', 
     'order': '2', 
    }, 
} 

我想補充一點,與「內容」鍵的array.I相信這點對應的值:

var things=[]; 
    for (x in $scope.object){ 
    things.push(x.content); 
    } 

它不起作用。它只是返回undefined。有任何想法嗎?

+0

[請看看這個討論] [1] [1]:http://stackoverflow.com/questions/921789/how-to-loop-through-javascript-object-literal-with-objects-as-members – caoglish

回答

1

x枚舉$scope.object的鍵,而不是數值。使用這個來代替:

things.push($scope.object[x].content); 
0
var things = [], x; 
for(x in $scope.object){ 
    if($scope.object.hasOwnProperty(x)){ 
     if($scope.object[x].content !== undefined){ 
      things.push($scope.object[x].content); 
     } 
    }  
} 

這包括如果您需要,以確保其工作的所有檢查。測試:

var $scope = {}; 
$scope.object = { 
    'thing1': { 
     'content': 'blah blah', 
     'order': '1', 
    }, 
    'thing2': { 
     'content': 'blah blah blah', 
     'order': '2', 
    } 
}; 

var things = [], x; 
for(x in $scope.object){ 
    if($scope.object.hasOwnProperty(x)){ 
     if($scope.object[x].content !== undefined){ 
      things.push($scope.object[x].content); 
     } 
    }  
} 

console.log(things);//logs ["blah blah", "blah blah blah"] 

Object.hasOwnProperty(propertyName)需要確保該對象實際上已經考慮到財產,.content確保該財產是存在的價值是不是不確定的。

在該實例:

for(var x in object) 

x實際上是屬性名稱,在這種情況下thing1thing2,如果目的是通過一個數組代替那麼x將每個對象的索引。的

0

,而不是再次寫入所有必要的檢查,你可以使用angularJS」包裝爲jquery.foreach:

live example

var result = [] 
angular.forEach($scope.object, function (value, key) { 
    result.push(value.content); 
});