0

I'm aware that properties in objects can be retrieved either .notation or wrapping key as a string expression in a [] suffix. for example

var character = {
   "name" : "Gloria",
   "feature" : "Dance"
};

console.log("using .notation: "+character.name);
console.log("using []suffix: "+character["name"]);

And it's works pretty well. But, When I do the same by retrieving values from an array of objects, .Notation is simply not working. The codes shows below.

var info = {
"full_name" : "Some Name",
"title" : "Some title",
"links" : [
        { "blog"     : "http://iviewsource.com" },
        { "facebook" : "http://facebook.com/iviewsource" },
        { "youtube"  : "http://www.youtube.com/planetoftheweb" },
        { "podcast"  : "http://feeds.feedburner.com/authoredcontent" },
        { "twitter"  : "http://twitter.com/planetoftheweb" }
    ]
};

then, when I try to retrieve values from each object in an array with the following snippet

for(var i = 0; i < info.links.length; i++) {
    for(var key in info.links[i]) {
        console.log("key is: "+key+" and it's value: "+info.links[i][key]);         
    }
}

In the above code, to retrieve the values I'm using info.links[i][key] and it's works as expected but if I use info.links[i].key, it just gives undefined which I'm not expected.
I wonder why? It confuses me a lot.

Kishore Kumar Korada
  • 1,204
  • 6
  • 22
  • 47

2 Answers2

0

key is not a property of that object, that is why it doesn't work. Key is another element with that key that you want to access.

In JavaScript,

obj.key

Would access the key property of obj object. However the following code,

obj["key"]

Would access the element at key "key". You should consider paying more attention to mapped values, also known as, Dictionary or Map.

Afzaal Ahmad Zeeshan
  • 15,669
  • 12
  • 55
  • 103
0

If you literally use info.links[i].key it won't work since there is no value associated with the key named key. If you meant something else, please edit the question to reflect that.

It is also a bit misleading to have a data structure where the name of the link is the key. Would be better to have keys name and link, then you could get them in the same way for every link, with info.links[i].name and info.links[i].link

Sami Kuhmonen
  • 30,146
  • 9
  • 61
  • 74