serializearray()jquery字段到行的JSON

时间:2015-06-23 14:15:25

标签: jquery json

我将serializearray() jquery用于序列化字段到JSON。它运行良好,但我需要按行,每行都有一个名为"matricula"的ID。

enter image description here

我需要一些像:

jsonObj = [{"matricula":"14002028","faltas":"1","calif":"9.30"},
           {"matricula":"14005038","faltas":"0","calif":"9.80"},
           {"matricula":"14005499","faltas":"2","calif":"9.50"}];

但是我的代码告诉了我:(

jsonObj = [{"matricula":"14002028","faltas":"1"},
           {"matricula":"14002028","calif":"9.5"},
           {"matricula":"14005038","faltas":"0"},
           {"matricula":"14005038","calif":"8.0"},
           {"matricula":"14005499","faltas":"2"},
           {"matricula":"14005499","calif":"10"}];

这是我的代码:

var dataString = jQuery('#frm_CapCalif').serializeArray(); // Send data forms

       jsonObj = [];   // create JSON object
 jQuery.each(dataString, function(i, field){ // get each value serialize
          item = {}
          item ["matricula"] = field.name.substr(0,8);          
            if (field.name.substr(8,1)==='F')

            item ["faltas"]  = field.value;
              else
            item ["calif"]  = field.value;


     jsonObj.push(item);
                                           });

注意:每个字段都被命名为matricula& F和matricula& C,显示“14005028F”和“14005028C”...... F表示faltas,C表示calif。

我觉得很困惑,有没有办法做到这一点更简单?感谢

2 个答案:

答案 0 :(得分:0)

仅当我不是奇数时才添加项目。像这样:

item = {};
jQuery.each(dataString, function(i, field){
     if (field.name.substr(8,1)==='F') item ["faltas"]  = field.value;
     else item ["calif"]  = field.value;

   if (i%2 != 0) {
    item ["matricula"] = field.name.substr(0,8);
    jsonObj.push(item);
    item = {};
   } 
});

答案 1 :(得分:0)

function groupByProperty(arr, prop) {
    var index = {}, output = [];
    $.each(arr, function (i, obj) {
        var propVal = obj[prop];
        if (!index.hasOwnProperty(propVal)) index[propVal] = {};
        index[propVal] = $.extend(index[propVal], obj);
    });
    $.each(index, function (key, value) {
        output.push(value);
    });
    return output;    
});

var test = [{"matricula":"14002028","faltas":"1"},
           {"matricula":"14002028","calif":"9.5"},
           {"matricula":"14005038","faltas":"0"},
           {"matricula":"14005038","calif":"8.0"},
           {"matricula":"14005499","faltas":"2"},
           {"matricula":"14005499","calif":"10"}];

groupByProperty(test, "matricula");