0

I'm trying to access data in my variable object:

foo = {
    tweet1 : [{
        user: {
            profile_image_url : "assets/avatar.png",
            name : "@Hodor"
        },
        text : "Hodor Hodor Hodor Hodor Hodor Hodor Hodor..... Hodor"
    }],
    tweet2 : [{
        user: {
            profile_image_url : "assets/avatar.png",
            name : "@johnsnow"
        },
        text : "Someone once said that I know nothing..."
    }],
    tweet3 : [{
        user: {
            profile_image_url : "assets/avatar.png",
            name : "@drwho"
        },
        text : "Fantastic!"
    }]
};

And I have my loop set up which gives me 3 objects:

for (var i in foo) {
    console.log( foo[ i ] );
}

However I am unsure how to access the data further and grab the text and user keys for each object. Thoughts?

u111937
  • 287
  • 4
  • 16
  • FYI, that's a pretty poor data structure. If `foo` just contains a bunch of tweets, it should be an array, not an object. At which point you can access the tweet objects by index. It's also unusual that each tweet is a single element array, shouldn't it just be an object? – Adam Jenkins Dec 09 '15 at 16:51

3 Answers3

2

You can keep iterating as deep as you want to go:

for (var key in foo) {
    for (var i = 0; i < foo[key].length; i++) {
        //Iterating each array of each object

        //Keys of each array
        for (var anotherKey in foo[key][i]) {
            console.log(foo[key][i][anotherKey]);
        }
    }
}
tymeJV
  • 103,943
  • 14
  • 161
  • 157
  • Awesome, worked like a charm. I thought I had to use another loop inside the loop, makes perfect sense. Cheers! – u111937 Dec 09 '15 at 16:59
0

To achieve this you simply have to refer to the nested object first. e.g.

 console.log(foo.tweet1[0]);

I hope that helps.

Dane
  • 312
  • 2
  • 10
0

This should do the trick...

for (var i in foo)
{
    console.log(foo[i][0].user);
}
eaCe
  • 199
  • 6