2

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)
}

1 Answer 1

5

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>`;     
  })
)
Sign up to request clarification or add additional context in comments.

4 Comments

${name} How does this part works? Any new arrival to ES6? Can you link me to the relevant doc?
@RajaprabhuAravindasamy Template strings
@RajaprabhuAravindasamy: Yes, that's a feature of template strings, which the OP used.
I feel extremely dumb now. @RajaprabhuAravindasamy template strings are so much better than the vanilla way in terms of productivity. Thank you for the answer. Will mark the answer correct when it lets me (time limit).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.