Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 3 of 3
  1. #1
    Regular Coder
    Join Date
    Jul 2010
    Location
    Sheffield
    Posts
    824
    Thanks
    93
    Thanked 18 Times in 18 Posts

    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?

  • #2
    Regular Coder
    Join Date
    Aug 2010
    Posts
    970
    Thanks
    19
    Thanked 212 Times in 210 Posts
    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)

  • #3
    Senior Coder Dormilich's Avatar
    Join Date
    Jan 2010
    Location
    Behind the Wall
    Posts
    3,278
    Thanks
    12
    Thanked 342 Times in 338 Posts
    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;
    }); 
    The computer is always right. The computer is always right. The computer is always right. Take it from someone who has programmed for over ten years: not once has the computational mechanism of the machine malfunctioned.
    André Behrens, NY Times Software Developer


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •