3

I am trying to walk through a JS object, with the for_in loop. That seems to be returning the found value (contentCard1) as plain text. I can't get it to print val.text

var contentCards = {
    contentCard1: {text: "text in here", date: "date in here"}
}

for(var val in contentCards) {
    console.log(val.text);
}

Logging val.text gives me undefined, and logging just val gives me contentCard1.

Thanks for helping.

smonff
  • 3,399
  • 3
  • 36
  • 46
g3ttr3kked
  • 31
  • 4
  • 1
    It's not really a duplicate of *that* question, though obviously there is overlap. – nnnnnn Mar 30 '17 at 08:55
  • @nnnnnn My apologies. :-) Would still hold the vote as dupe answers how to loop over nested object. – Rajesh Mar 30 '17 at 08:56

2 Answers2

2

With for ... in, you are iterating over the keys of contentCards. For the access you need the object and the key with bracket notation.

contentCards[val].text
//          ^^^^^

var contentCards = { contentCard1: { text: "text in here", date: "date in here" } };

for (var val in contentCards) {
    console.log(contentCards[val].text);
}
.as-console-wrapper { max-height: 100% !important; top: 0; }
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
0

Used this:

 var contentCards = {
            contentCard1: { text: "text in here", date: "date in here" }
        }

     alert(contentCards.contentCard1.text);
Amol B Lande
  • 242
  • 1
  • 2
  • 13
  • Huh? What's the point of a loop if you don't use the iterator variable and instead directly access a specific nested property? – nnnnnn Mar 30 '17 at 09:19
  • yes. but i think you have contentCards as list – Amol B Lande Mar 30 '17 at 09:40
  • Again, if you have `val in contentCards` and then never use `val`, what's the point of the loop? Every iteration would alert the same, specific value. – nnnnnn Mar 30 '17 at 09:45