for(t in favBooks) console.log(favBooks[t].Title);
Getting specific properties with for-in loop
-
28-09-2022 - |
Domanda
Is the 'for in' loop limited to showing only property names, and their first values, or is there a way for you see inside their values values? For example,
if i want to check the 'titles' property values inside of 'no1' object, that is located in 'favBooks' object, can i do it with for in loop?
I was trying something like this:
var favBooks = {
no1:{Title:'Sidhartha',Author:'Hesse'},
no2:{Title:'Cosmos',Author:'Sagan'},
no3:{Title:'Idiot',Author:'Dostojevski'}
}
and then calling only the titles with for in:
for(t in favBooks) console.log(favBooks[t.title]);
..but it returns undefined.
I know there are other ways to do this, but my question is: Is this the limitation of 'for in' - to only return property names and their first values, or can you go deeper into properties,and if yes - how?
Thanks
Soluzione
Altri suggerimenti
The problem is in the line console.log(favBooks[t.title]);`
Aside from having "title" instead of "Title" (javascript is case-sensitive), the property "Title" isn't an index of the object favBooks. You might be able to index it with favBooks["no1"] (I haveb't tried that) but you definitely could with favBooks.no1
eg
favBooks.no1.Title would be "Sidhartha".
so I think that last line should be:
for(t in favBooks) console.log(favBooks[t].Title); // logs the Title property
The function below runs through a javascript object and makes a string representation of it. If you alert the result, it'll reveal the structure of the object. Also it traverses the object with
for (X in el)
where el is any object- be it a DIV element in the html doc or a {a:b,c:d} type object.
perhaps that will help ?
function dump(el) {
var s=""; //
for (X in el) {
if (el[X]) {var sX=el[X].toString(); s+=X+": "+el[X] + "<br>\n"}
}
return s
}
Maybe you want something closer to PHP foreach ($array as $key => $value)
:
var favBooks = [ // <-- note this is now an array
{Title:'Sidhartha',Author:'Hesse'},
{Title:'Cosmos',Author:'Sagan'},
{Title:'Idiot',Author:'Dostojevski'}
]
favBooks.forEach (function(elt){ console.log (elt.Title); })
Note that this will not work on IE8-