Niklas
Niklas

Reputation: 13135

Create list from JSON objects

I need to create a list on the form

<li>
    <span class="room">A20</span>
    <span class="dropin">3</span>
    <span class="appoint">1</span>
    <span class="delay">20</span>
</li>
<li>
    <span class="room">A21</span>
    <span class="dropin">2</span>
    <span class="appoint">1</span>
    <span class="delay">10</span>
</li>

using the values from a json object on the form.

data = [
    { "name": "A20 Dropin", "queueType": "QUEUE", "customers": 3, "delay": 0 },
    { "name": "A20 Appoint", "queueType": "APP_QUEUE", "customers": 1, "delay": 20 },
    { "name": "A21 Appoint", "queueType": "APP_QUEUE", "customers": 1, "delay": 10 },
    { "name": "A21 Dropin", "queueType": "QUEUE", "customers": 2, "delay": 0 }
];

The problem is getting the name (e.g. A20) from every other object but still getting the customers from every object.

I've set up an example in jsfiddle here! But the code prints every object and not on the form I'd like.

Upvotes: 0

Views: 1305

Answers (2)

Arun P Johny
Arun P Johny

Reputation: 388326

Try

//normalize the data
var map = {}, array = [];
$.each(data, function (idx, value) {
    var key = value.name.match(/^.\d+/)[0];
    var item = map[key];
    if (!item) {
        item = {
            key: key,
            name: value.name
        };
        map[key] = item;
        array.push(item)
    }
    if (value.queueType == 'QUEUE') {
        item.dropin = value.customers;
    } else if (value.queueType == 'APP_QUEUE') {
        item.appoint = value.customers;
        item.delay = value.delay
    }
})

var html = $.map(array, function (item) {
    return '<li><span class="room">' + item.key + '</span><span class="dropin">' + item.dropin + '</span><span class="appoint">' + item.appoint + '</span><span class="delay">' + item.delay + '</span></li>';
}).join('');
$('ul').append(html);

Demo: Fiddle

Upvotes: 2

Parv Sharma
Parv Sharma

Reputation: 12705

$(data).each(function(i,v){
 var a = v.name.split()[0];
 var d = v.name.split()[1];
 var $span = $('span[data-a="'+a+'"]');
 var $li = null;
 if(span.length){
   $li = $span.closest('li');
 }
 else{
   //create li and whole of the structure
   $li = $('<li></li>');
 }

 //do rest of the dom changes here based on the value of d
 ....
 //at last
 $cont.append($li)/*the container element*/
});

Upvotes: 0

Related Questions