Go Back   CodingForums.com > :: Client side development > JavaScript programming > DOM and JSON scripting

Before you post, read our: Rules & Posting Guidelines

Reply
 
Thread Tools Rate Thread
Enjoy an ad free experience by logging in. Not a member yet? Register.
Old 12-04-2012, 03:42 PM   PM User | #1
tomharto
Regular Coder

 
Join Date: Jul 2010
Location: Sheffield
Posts: 794
Thanks: 91
Thanked 18 Times in 18 Posts
tomharto is on a distinguished road
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?
tomharto is offline   Reply With Quote
Old 12-04-2012, 04:03 PM   PM User | #2
DaveyErwin
Regular Coder

 
Join Date: Aug 2010
Posts: 806
Thanks: 12
Thanked 168 Times in 166 Posts
DaveyErwin is on a distinguished road
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)
DaveyErwin is offline   Reply With Quote
Old 12-05-2012, 11:27 AM   PM User | #3
Dormilich
Senior Coder

 
Dormilich's Avatar
 
Join Date: Jan 2010
Location: Behind the Wall
Posts: 2,857
Thanks: 9
Thanked 288 Times in 284 Posts
Dormilich is on a distinguished road
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;
}); 
__________________
please post your code wrapped in [CODE] [/CODE] tags
Dormilich is offline   Reply With Quote
Reply

Bookmarks

Jump To Top of Thread


Thread Tools
Rate This Thread
Rate This Thread:

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off

Forum Jump


All times are GMT +1. The time now is 01:49 AM.


Advertisement
Log in to turn off these ads.