循环以将JSON值添加到数组

时间:2013-07-16 01:36:34

标签: javascript json angularjs

我有一个像这样的JSON对象:

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

我想将与'content'键对应的值添加到数组中。我认为这样可行:

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

它不起作用。它只返回undefined。有什么想法吗?

3 个答案:

答案 0 :(得分:1)

x枚举$scope.object的键,而不是值。请改用:

things.push($scope.object[x].content);

答案 1 :(得分: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将是每个对象的索引。

答案 2 :(得分:0)

而不是再次写入所有需要的检查,你可以使用angularJS'包装器来获取jquery.foreach:

live example

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