I'm still new to learning loops so I'm a little confused. I have a for...in
loop that loops a json file of objects. Then I have jQuery create some html elements for each object. I have one problem though, every time it loops, it repeats the previous objects along with the new one so the output becomes:
-name
-name
-test
-name
-test
-someone
-name
-test
-someone
-something
But I'm trying to do
-name
-test
-someone
-something
How can I achieve this?
My current code for it is this:
var html = ""
for (var name in urls) {
html += `<div class='card-panel white'><div class='container'><div class='row'><div class='input-field col s12'> ${name} <br> ${urls[name].url} </div></div></div></div>`
$("#main").append(html)
}
You are appending HTML string on each iteration instead append entire code outside the for loop. Although use Object#hasOwnProperty
for getting only own properties and not its prototypes.
var html = ""
for (var name in urls) {
if(urls.hasOwnProperty(name))
html += `<div class='card-panel white'><div class='container'><div class='row'><div class='input-field col s12'> ${name} <br> ${urls[name].url} </div></div></div></div>`;
}
$("#main").append(html)
I think it would be better to use Object.keys()
and String#map
methods.
$("#main").append(
Object.keys(urls).map(function(name){
return `<div class='card-panel white'><div class='container'><div class='row'><div class='input-field col s12'> ${name} <br> ${urls[name].url} </div></div></div></div>`;
})
)