Billy Billy - 1 month ago 9
HTML Question

Append HTML Element from Object Property

I'm working on my little code.
I want to append some HTML element from my array object.
These are my codes.

HTML

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
<div class="container">
</div>
</body>
</html>


Javascript

var obj=[
{
name: "john",
phone: "0831",
tasks:["run","slide"]
},
{
name: "billy",
phone: "0798",
tasks: ["swim", "fly", "crawl"]
}
]

var str="";

for(i=0;i<obj.length;i++){
str+='<div>';
str+='<h1>'+obj[i].name+'</h1>';
str+='<p>'+obj[i].phone+'</p>';
str+='<ul>'
str+='<li>'+obj[i].tasks[0]+'</li>';
str+='<li>'+obj[i].tasks[1]+'</li>';
str+='<li>'+obj[i].tasks[2]+'</li>';
str+='</ul>'
str+='</div>';

$(".container").html(str);
}


Problem

The problem is when i want to append tasks object property on multiple li element, there's one undefined property because of the different between property amount.

Recent Output

<div class="container">
<div>
<h1>john</h1>
<p>0831</p>
<ul>
<li>run</li>
<li>slide</li>
<li>undefined</li>
</ul></div>
<div>
<h1>billy</h1>
<p>0798</p>
<ul>
<li>swim</li>
<li>fly</li>
<li>crawl</li>
</ul>
</div>
</div>


Question

My question is how to append li element to be the same amount as object property, so there's no more undefined property like i mention above?

Answer

Maybe like this

...
str+='<ul>'
for (var ii = 0; ii < obj[i].tasks.length; ii++) {
    str+='<li>'+obj[i].tasks[ii]+'</li>';
}
str+='</ul>'
...