CodingForums.com

CodingForums.com (http://www.codingforums.com/index.php)
-   DOM and JSON scripting (http://www.codingforums.com/forumdisplay.php?f=15)
-   -   How do I loop through this JSON? (http://www.codingforums.com/showthread.php?t=283538)

tomharto 12-04-2012 03:42 PM

How do I loop through this JSON?
 
The JSON that I get returned is this.

[{"name":"hpfa","addressLine1":"","addressLine2":"","town":"","county":"","postcode":"","contactName" :"","email":"","tel":"01442 766 285"},{"name":"hartford","addressLine1":"","addressLine2":"","town":"","county":"","postcode":"","co ntactName":"","email":"","tel":""},{"name":"hampshire","addressLine1":"","addressLine2":"","town":"" ,"county":"","postcode":"","contactName":"","email":"","tel":""}]

I need to loop through it and add each of the name elements to a javascript array. How would i do this?

DaveyErwin 12-04-2012 04:03 PM

Code:


a=[{"name":"hpfa","addressLine1":"","addressLine2":"","town":"","county":"","postcode":"","contactName" :"","email":"","tel":"01442 766 285"},{"name":"hartford","addressLine1":"","addressLine2":"","town":"","county":"","postcode":"","co ntactName":"","email":"","tel":""},{"name":"hampshire","addressLine1":"","addressLine2":"","town":"" ,"county":"","postcode":"","contactName":"","email":"","tel":""}]
names=[]
for(i in a)names.push(a[i].name)
alert(names)


Dormilich 12-05-2012 11:27 AM

since it is an array, I would advice to use a standard for() loop, not a for…in loop. anyways, there are also array methods to do the same.
PHP Code:

var = [{"name":"hpfa","addressLine1":"", ... ];
var 
names a.map(function(item) {
    return 
item.name;
}); 



All times are GMT +1. The time now is 03:17 PM.

Powered by vBulletin®
Copyright ©2000 - 2013, Jelsoft Enterprises Ltd.