Q:

Format returned table data in json

I'm fairly new to javascript.  I retreive data from a sql server database that looks like this :
[Object { shortcode="0013A2004031AC9A", latest_measurement=1067, keyid="6801"}, 
 Object { shortcode="0013A2004031AC9A", latest_measurement=7, keyid="6802"}, 
 Object { shortcode="0013A2004031AC9A", latest_measurement=8598838, keyid="6803"}]

I want to format this in a json like this :
{mac : 0013A2004031AC9A, keys : {6801:1067, 6802:7, 6803:8598838}}

but I just don't get to that. 
I have 
var jsonDataPerMac = {};

I loop over the json object above and for every new mac I find I do :
 jsonDataPerMac[i]={"mac": device.shortcode, "keys":[]};

but how do I get to fill the keys? 
Any hints would be appreciated.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);
          });
}});

A:

Here is my proposition.  I would rather avoid using jQuery to perform such a simple operations.  In this particular example, we use forEach and for..in loop.   
//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);

You can transform above code to a function and then, reuse it in your ajax onSuccess method.  Remember to pass the array as an argument and to return newArray. 
JSFiddle:
http://jsfiddle.net/2d5Vq/2/

