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.

2
  • 1
    It's not really a duplicate of that question, though obviously there is overlap. Commented Mar 30, 2017 at 8:55
  • @nnnnnn My apologies. :-) Would still hold the vote as dupe answers how to loop over nested object. Commented Mar 30, 2017 at 8:56

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

Comments

0

Used this:

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

     alert(contentCards.contentCard1.text);

3 Comments

Huh? What's the point of a loop if you don't use the iterator variable and instead directly access a specific nested property?
yes. but i think you have contentCards as list
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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.