2010-09-13 12 views
5

Ho bisogno di assistenza per accedere a un array nidificato che si trova il mio Data Set JSON. Ecco la prima voce di mia top a livello di array JSON:Come faccio a fare riferimento a un array annidato all'interno dei miei dati JSON?

{ 
    "pingFeed": [{ 
     "header": "Get Drinks?", 
     "picture": "images/joe.jpg", 
     "location": "Tartine's, SF", 
     "time": "Tomorrow Night", 
     "name": "Joe Shmoe", 
     "pid": 
     "123441121", 
     "description": "Let's drop some bills, yal!", 
     "comments": [{ 
      "author": "Joe S.", 
      "text": "I'm Thirsty" 
     }, 
     { 
      "author": "Adder K.", 
      "text": 
      "Uber Narfle" 
     }, 
     { 
      "author": "Sargon G.", 
      "text": "taeber" 
     }, 
     { 
      "author": "Randy T.", 
      "text": "Powdered Sugar" 
     }, 
     { 
      "author": "Salvatore D.", 
      "text": 
      "Chocolate with Sprinkles" 
     }, 
     { 
      "author": "Jeff T.", 
      "type": "Chocolate" 
     }, 
     { 
      "author": "Chris M.", 
      "text": "Maple" 
     }], 
     "joined": false, 
     "participants": [ 
     "Salvatore G.", "Adder K.", "Boutros G."], 
     "lat": 37.25, 
     "long": 122, 
     "private": true 
    }] 
} 

vorrei sapere come posso accedere ai dati commenti e dei partecipanti utilizzando la seguente notazione:

for (var k = 0; k < pingFeed.length ; k++) { 
    console.log(pingFeed[k].comments); 
    console.log(pingFeed[k].participants); 
} 

Attualmente questa forma di dot notation funziona per le altre voci nell'array JSON ... Sto cercando di restituire tutti questi dati come stringhe.

+2

Tartine è un'ottima soluzione Taurant, scusa non ho potuto resistere. –

+0

ho avuto solo le loro torte. – Sachin

risposta

1

Non sono sicuro di tutto quello che stai cercando da fare, ma forse questo ti indirizzerà nella giusta direzione:

for (var k = 0; k < pingFeed.length; k++) { 
    for (var i = 0; i < pingFeed[k].comments.length; i++) { 
     var oComments = pingFeed[k].comments[i]; 
     console.log(oComments.author + ": " + oComments.text); 
    } 
    console.log(pingFeed[k].participants.join(", ")); 
} 
0

Non c'è niente di sbagliato con il tuo codice: pingFeed[k].comments restituirà array e pingFeed[k].comments[0] restituirà il primo commento da quell'array.

provare qui
http://jsfiddle.net/U8udd/

1

Bene, comments e participants sono array, in modo da potervi accedere come array normali, ad esempio:

for (var k = 0; k < pingFeed.length ; k++) { 
    var comments = pingFeed[k].comments; 
    for(var i = 0, length = comments.length; i < length; ++i) { 
     console.log(comments[i]); 
    } 
} 
Problemi correlati