5

I need assistance in accessing a nested array located my JSON Data Set. Here is the first entry of my top-level JSON array:

{
    "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
    }]
}

I would like to know how I can access the comments and participants data using the following notation:

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

Currently this form of dot notation is working for the other entries in the JSON array... I am looking to return all of these data as Strings.

1
  • 2
    Tartine is a great restaurant, sorry I couldn't resist. Commented Sep 13, 2010 at 23:05

3 Answers 3

1

I'm not sure quite what you're looking to do, but perhaps this will point you in the right direction:

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(", "));
}
Sign up to request clarification or add additional context in comments.

Comments

1

Well, comments and participants are arrays, so you can access them like normal arrays, e.g.:

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]);
    }
}

Comments

0

There's nothing wrong with your code: pingFeed[k].comments will return array and pingFeed[k].comments[0] will return first comment from that array.

Try here
http://jsfiddle.net/U8udd/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.