I've been trying to convert this object to an unordered list, but I need to consolidate it in categories.
var snippets = [
{title: 'snippet 1', content: 'hello there 1', category: 'javascript'},
{title: 'snippet 2 ', content: 'hello there 2', category: 'wordpress'},
{title: 'snippet 3', content: 'hello there 3', category: 'javascript'},
{title: 'snippet 4', content: 'hello there 4', category: 'general'},
{title: 'snippet 5', content: 'hello there 5', category: 'general'}
];
The expected output is:
<ul>
<li>javascript
<ul>
<li>snippet 1</li>
<li>snippet 2</li>
</ul>
</li>
<li>wordpress
<ul>
<li>snippet 1</li>
<li>snippet 2</li>
</ul>
</li>
</ul>
I've been trying to do it with $.each
, but for the file of me I can't get my head around it. I'm willing to use UnderscoreJS too.
$('body').append('<ul class="categories"></ul>');
$.each(snippets, function(i, v) {
var data = '<li class="category">'+ v.category +' ';
data += '<ul class="item"> <li> ' + v.title + ' </li> </ul>';
data += '</li>';
$(data).appendTo('.categories');
});
Output not expected:
<ul class="categories">
<li class="category">javascript
<ul class="item">
<li> snippet 1 </li>
</ul></li>
<li class="category">wordpress
<ul class="item">
<li> snippet 2 </li>
</ul>
</li>
<li class="category">javascript
<ul class="item">
<li> snippet 3 </li>
</ul>
</li>
<li class="category">general
<ul class="item">
<li> snippet 4
</li>
</ul>
</li>
<li class="category">general
<ul class="item">
<li> snippet 5
</li>
</ul>
</li>
</ul>
Can anyone give me a hint?