格式化在json中返回的表数据

时间:2014-04-26 14:43:26

标签: javascript json

我对javascript很新。我从sql server数据库中检索数据,如下所示:

[Object { shortcode="0013A2004031AC9A", latest_measurement=1067, keyid="6801"}, 
 Object { shortcode="0013A2004031AC9A", latest_measurement=7, keyid="6802"}, 
 Object { shortcode="0013A2004031AC9A", latest_measurement=8598838, keyid="6803"}]

我想在json中格式化这个:

{mac : 0013A2004031AC9A, keys : {6801:1067, 6802:7, 6803:8598838}}

但我还没有达到目的。

我有

var jsonDataPerMac = {};

我遍历上面的json对象,并为我发现的每个新mac:

 jsonDataPerMac[i]={"mac": device.shortcode, "keys":[]};

但如何填写钥匙? 任何提示都将不胜感激。enter code here

var macs =  [];
var jsonDataPerMac = {};
var i = 0;            

$.ajax({
    url: "/bmmeasurements",
    type: "GET",
    data: {"unitid" : unitid},
    async: false,
    success: function (data) {
    console.log(data);

    initializeTable();

    $.each(data, function (index,device) {
     //add all distinct macs in an array, to use them as a column header
     if($.inArray(device.shortcode, macs) == -1) {
          macs.push(device.shortcode);
          jsonDataPerMac[i]={"mac": device.shortcode, "keys":[]};
          i++;

          //create a table cell for each possible key. id = 'mac-key'
          createTableGrid(device.shortcode);
          }

          //add the measurement data to the correct cell in the grid 
       $('#' + device.shortcode + '-' + device.keyid).html(device.latest_measurement);
          });
}});

2 个答案:

答案 0 :(得分:0)

您需要首先合并条目......

var reducedData = {};
$.each(macs, function(index,macitem){
    if (reducedData.hasOwnProperty(macitem.shortcode)) {
        reducedData[macitem.shortcode].push(macitem.key);
    } else {
        reducedData[macitem.shortcode] = [ macitem.key ];
    }
});

然后在数组中映射到您想要的格式......

var jsonDataPerMac = [],
    i = 0;
$.map(reducedData, function(keys,mac){
    jsonDataPerMac[i++] = {"mac": mac, "keys": keys};
    // your other code goes here
});

此外,您对jsonDataPerMac的使用表明您希望它是一个数组。

答案 1 :(得分:0)

这是我的主张。我宁愿避免使用jQuery来执行这么简单的操作。在此特定示例中,我们使用forEachfor..in循环。

//new output array
var newArray = [];

//we traverse the array received from AJAX call
array.forEach(function(el) {
    var added = false; // it's false by default

    // we check if the mac is already in newArray, if yes - just add the key
    for(var i in newArray) {
        if(newArray[i].mac == el.shortcode) {
           newArray[i].keys.push(el.keyid+":"+el.latest_measurement);
           added = true; // tells us whether the key has been added or not
        } 
    }

    // if key hasn't been added - create a new entry
    if(!added) {
        newArray.push({"mac": el.shortcode, "keys":[el.keyid+":"+el.latest_measurement]});
    }
});

console.log(newArray);

您可以将上面的代码转换为函数,然后在您的ajax onSuccess方法中重用它。记得将数组作为参数传递并返回newArray。

<强>的jsfiddle http://jsfiddle.net/2d5Vq/2/

相关问题