Tom
Tom

Reputation: 734

How to loop through JSON (with AngularJS) and put the results in a Javascript array?

Using the latest AngularJS version (1.3.0-rc.5), I am retrieving a simple JSON object containing people's names. Example of the JSON object:

[{'id':1, 'name':'John'}, {'id':2, 'name':'Jane'}, {'id':3, 'name':'Pete'}]

I cannot figure out how to put all the names into an associative Javascript array. In my mind I want to create an empty Javascript array and loop through the JSON object, and using .push() in the loop to keep adding the names to the array. But I cannot get this working in AngularJS.

ps. I'll accept the answer that helps me out with this.

Upvotes: 0

Views: 2969

Answers (4)

Gautam Bhalla
Gautam Bhalla

Reputation: 1210

Use angular.fromJson() function to solve this.

Upvotes: -2

UltraInstinct
UltraInstinct

Reputation: 44444

Use map(..) on your array object.

var obj = [{'id':1, 'name':'John'}, {'id':2, 'name':'Jane'}, {'id':3, 'name':'Pete'}];
var result = obj.map(function (x) {return x["name"]; });
//["John", "Jane", "Pete"]

Upvotes: 2

Vaibhav
Vaibhav

Reputation: 1477

You can do this in pure javascript

var arr = [{'id':1, 'name':'John'}, {'id':2, 'name':'Jane'}, {'id':3, 'name':'Pete'}];
var nameArr =[];
arr.forEach(
function(elem){ 
  nameArr.push(elem.name);
});

Upvotes: 3

Deleteman
Deleteman

Reputation: 8690

Angular is not meant to help you with this, Angular is meant for other parts of the application (UI for instance). If you want to do this, in JS it's simple:

var list = [{'id':1, 'name':'John'}, {'id':2, 'name':'Jane'}, {'id':3, 'name':'Pete'}]
var names = []
for(var idx in list) {
  names.push(list[idx]['name'])
}

You also mentioned an associative array, in JS you have objects, which work similarly, but I don't understand how you want to use them... what is the index for that associative array? The name? If that's the case, then what is the value? is it the ID? If so, you could do something like this:

var list = [{'id':1, 'name':'John'}, {'id':2, 'name':'Jane'}, {'id':3, 'name':'Pete'}]
var names = {} //object literal
for(var idx in list) {
  names[list[idx]['name']] = list[idx]['id']
}

Hope that helps

Upvotes: 4

Related Questions