Convert data from received JSON format to JVectorMap format

561 views Asked by At

I am developing dashboard of a MIS in MVC 5, and in that dashboard I want to use JVectorMap to load the registered countries. So following is my controller action that returns the JSON

public JsonResult registeredCountries()
{               
    var ret = db.View_RegisteredCountries.Select(x => new { Key = x.CountryCode, Value = x.TotalCompanies }).ToDictionary(x => x.Key, x => x.Value).ToList();

    return Json(ret, JsonRequestBehavior.AllowGet);
}

and following is my JS code to get the JSON

var data = {};
$.ajax({
    url: 'registeredCountries',
    type: 'GET',
    traditional: true,
    async: false,
    cache: false,
    //async: false,
    dataType: 'json'
}).done(function(result) {
    data = result;
});

But my problem is that JVectorMap use the array in the following format

data_array = {
    "US": 4977,
    "AU": 4873,
    "IN": 3671,
    "BR": 2476,
    "TR": 1476,
    "CN": 146,
    "CA": 134,
    "BD": 100
};

but the returned JSON is in the following format

[{ "Key": "SA", "Value": 4 }]

How do I convert the above JSON to the following format so that JVectorMap could be populated.

data_array = {
    "SA":4
}
1

There are 1 answers

0
Vanquished Wombat On BEST ANSWER

Simply a matter of walking the array of inputs and create an object from each entry.

// set up some sample data - in your case you already have this.
var data = JSON.parse('[{"Key":"SA","Value":4},{"Key":"US","Value":12},{"Key":"BR","Value":6}]')

var obj={}  // make a new object to build results.
for (var i =0; i < data.length; i = i + 1) {
  
  obj[data[i].Key] = data[i].Value

  }

// Note jquery only used for this debug output.
$("#output").html(JSON.stringify(obj))
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='output'></div>