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 trialMindaugas Dragunas
Full Stack JavaScript Techdegree Student 16,169 PointsLoop 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
231,172 PointsYou 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
Full Stack JavaScript Techdegree Student 16,169 PointsMindaugas Dragunas
Full Stack JavaScript Techdegree Student 16,169 PointsThank 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
231,172 PointsSteven Parker
231,172 PointsA database would be a good idea, particularly if the content will be large and/or change often.