Claudius Rehme
Claudius Rehme

Reputation: 57

jQuery: Building up ul from json objects seperated by specific key

My ajax function gives back several JSON objects that have the following pattern:

var data = [
    { 'category': 3, 'name': 'Max' },
    { 'category': 1, 'name': 'John' },
    { 'category': 2, 'name': 'Mary' },
    { 'category': 2, 'name': 'Dennis' },
    { 'category': 1, 'name': 'Louis' }
];

Objects with the same category can have different names.

My goal is to build up a list based on these objects SORTED by category with jQuery. Here is what the list should finally look like:

<ul class="list">
    <li class="category-divider">1</li>
    <li class="element">John</li>
    <li class="element">Louis</li>
    <li class="category-divider">2</li>
    <li class="element">Mary</li>
    <li class="element">Dennis</li>
    <li class="category-divider">3</li>
    <li class="element">Max</li>
</ul>

What is the fastest and most flexible way to achieve building up this list based on an array like the one provided above?

Upvotes: 0

Views: 139

Answers (1)

juvian
juvian

Reputation: 16068

var data = [{
    'category': 3,
    'name': 'Max'
}, {
    'category': 1,
    'name': 'John'
}, {
    'category': 2,
    'name': 'Mary'
}, {
    'category': 2,
    'name': 'Dennis'
}, {
    'category': 1,
    'name': 'Louis'
}];


var list = $("<ul></ul>") // create list
var groupedData = {};
for (var i = 0; i < data.length; i++) { // group names by category
    groupedData[data[i].category] = groupedData[data[i].category] || []; // check if it exists, if not set it as empty array
    groupedData[data[i].category].push(data[i].name)
}

var categories = Object.keys(groupedData).sort(function(a,b){ return a -b}) // sort categories

for (var j = 0; j < categories.length; j ++) {
    var cat = categories[j]
    var category = $("<li class='category-divider'>" + cat + "</li>") // create category divider
    for (var i = 0; i < groupedData[cat].length; i++) {
        category.append("<li class='element'>" + groupedData[cat][i] + "</li>") // add names
    }
    list.append(category) // add category to list
}
$("body").append(list) // add list to body
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>

Upvotes: 1

Related Questions