0

I have a JSON object like so:

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

I would like to add the values that correspond with the 'content' keys to an array.I thought this would work:

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

It does not work. It just returns undefined. Any ideas?

  • [Please look at this discussion][1] [1]: http://stackoverflow.com/questions/921789/how-to-loop-through-javascript-object-literal-with-objects-as-members – caoglish Jul 16 '13 at 01:44

3 Answers3

1

x enumerates the keys of $scope.object, not the values. Use this instead:

things.push($scope.object[x].content);
Marcelo Cantos
  • 181,030
  • 38
  • 327
  • 365
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);
        }
    }    
}

This covers all checks you should require to make sure its working. Tested:

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) is required to make sure that the object has actually been given that property, .content makes sure that the property is there and the value is not undefined.

In the instance of:

for(var x in object)

x is actually the property name, in this case thing1 and thing2, if object is replaced by an array then x will be the index of each object.

FabianCook
  • 20,269
  • 16
  • 67
  • 115
0

instead of writing again all the needed checks, you can use angularJS' wrapper for jquery.foreach:

live example

var result = []
angular.forEach($scope.object, function (value, key) {
    result.push(value.content);
});
Eduard Gamonal
  • 8,023
  • 5
  • 41
  • 46