Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

Mindaugas Dragunas
seal-mask
.a{fill-rule:evenodd;}techdegree
Mindaugas Dragunas
Full Stack JavaScript Techdegree Student 16,169 Points

Loop thru JavaScript Objects

Hello,

How can I loop thru the Object? And what is the best way to do it if I want to add content, title and author in object and show in website one by one, like news feed or something like that.

Or there is no way to do it with java?

This is what i did, but it displays ony last items in object.

/////////////////////////////////////////////////

const topoc = document.getElementById('topoc'); const content = document.getElementById('content'); const author = document.getElementById('author');

const kokteiliai = { topic: "Kruvinoji Meri", content: "lorem ipsum naudingas tekstas, eina namo, nes nespejo pareiti namo", author: "Minde",

topic: "Namas", content: "lorem ipsum naudingas tekstas, eina namo, nes nespejo pareiti namo", author: "Loreta" };

const keys = Object.keys(kokteiliai) for (const key of keys) { topoc.innerHTML = kokteiliai.topic; content.innerHTML = kokteiliai.content; author.innerHTML = kokteiliai.author; }

/////////////////////////////////////////////////

1 Answer

Steven Parker
Steven Parker
229,732 Points

You can only have one attribute with a specific key in an object, so when you use the same key more than once in your object literal, the latest one of each key will be the only one saved.

For example, in your "kokteiliai" object, "author" is set to "Minde" but later it is set to "Loreta". So the value of "author" will be "Loreta". Perhaps you intended to create an array containing multiple objects?

Then in the loop, the variable "key" is created to hold the current item in each iteration, but it is never used in the loop body. So the loop just does the same thing over and over for the number of keys.

Mindaugas Dragunas
seal-mask
.a{fill-rule:evenodd;}techdegree
Mindaugas Dragunas
Full Stack JavaScript Techdegree Student 16,169 Points

Thank you for your answer. I just was thinkink yesterday what I just change value.

So with my toughts if i want to create this kind of think I probalby need to use database, where I could store all my news and only then call them with sertain code. Is that right?

Steven Parker
Steven Parker
229,732 Points

A database would be a good idea, particularly if the content will be large and/or change often.