Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I access object properties in a for loop in javascript?

I can't find anything that explains clearly what is wrong and what I should do.

I have this array:

const pages = [
{ 
    url: "/",
    page: 'pages/home.html',
    title: "Home" },
{ 
    url: "/recordings",
    page:'pages/recordings.html',
    title: "Recordings" },
{ 
    url: "/editions",
    page: 'pages/editions.html',
    title: "Editions" },
{ 
    url: "/videos",
    page: 'pages/videos.html',
    title: "Videos" },
]

I'm trying to loop it through with a for loop. page.url returns "undefined" in the console. But the "Test URL" console log returns a url string as expected. Why? What do I do? I want the page.url in the foor loop.

console.log("Pages: " + pages)
console.log("Test URL: " + pages[1].url)
for (page in pages) {

    console.log("Page: " + page)
    console.log("Page URL: " + page.url)
}
like image 877
coding_pianist Avatar asked Oct 19 '25 07:10

coding_pianist


2 Answers

You could use a for ... of statement, where you get the element of the array instead of the index by using a for ... in statement.

const pages = [{ url: "/", page: 'pages/home.html', title: "Home" }, { url: "/recordings", page: 'pages/recordings.html', title: "Recordings" }, { url: "/editions", page: 'pages/editions.html', title: "Editions" }, { url: "/videos", page: 'pages/videos.html', title: "Videos" }];

for (var page of pages) {
    console.log("Page: " + page.page);
    console.log("Page URL: " + page.url);
}
.as-console-wrapper { max-height: 100% !important; top: 0; }
like image 73
Nina Scholz Avatar answered Oct 20 '25 20:10

Nina Scholz


for..in is a method for iterating over "enumerable" properties of an object.

With arrays using for..in reveals the indexes:

const pages=[{url:"/",page:'pages/home.html',title:"Home"},{url:"/recordings",page:'pages/recordings.html',title:"Recordings"},{url:"/editions",page:'pages/editions.html',title:"Editions"},{url:"/videos",page:'pages/videos.html',title:"Videos"}]

for (let index in pages) {
  console.log(index);
  console.log(pages[index].page);
}

for..of can be used to iterate over "iterable" collections. This acts like a .forEach() function:

const pages=[{url:"/",page:'pages/home.html',title:"Home"},{url:"/recordings",page:'pages/recordings.html',title:"Recordings"},{url:"/editions",page:'pages/editions.html',title:"Editions"},{url:"/videos",page:'pages/videos.html',title:"Videos"}]

for (let page of pages) {
  console.log(page);
  console.log(page.page);
}
like image 34
Luca Kiebel Avatar answered Oct 20 '25 21:10

Luca Kiebel