从JSON对象创建列表

时间:2013-10-30 11:56:01

标签: jquery json

我需要在表单上创建一个列表

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

使用表单上json对象的值。

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 }
];

问题是从每个其他对象获取名称(例如A20),但仍然从每个对象获取客户。

  • 延迟总是来自APP_QUEUE。
  • 总有一对房间,例如 A20 Dropin A20 Appoint
  • 对象可能没有按顺序排列,所以我需要首先对它们进行排序,可能是在名称上。

我已设置an example in jsfiddle here!但代码会打印每个对象而不是我想要的表单。

2 个答案:

答案 0 :(得分:2)

尝试

//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);

演示:Fiddle

答案 1 :(得分:0)

$(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*/
});