Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

for_in loop for nested object javascript don't return expected values [duplicate]

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.

like image 485
g3ttr3kked Avatar asked Mar 27 '26 23:03

g3ttr3kked


1 Answers

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; }
like image 106
Nina Scholz Avatar answered Mar 30 '26 13:03

Nina Scholz