将接收到的 JSON 格式的数据转换为 JVectorMap 格式

Convert data from received JSON format to JVectorMap format

我正在 MVC 5 中开发 MIS 仪表板,在该仪表板中我想使用 JVectorMap 加载注册国家/地区。所以以下是我的控制器操作 returns 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);
}

下面是我获取 JSON

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

但我的问题是 JVectorMap 使用以下格式的数组

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

但返回的JSON格式如下

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

如何将上面的 JSON 转换为以下格式,以便可以填充 JVectorMap。

data_array = {
    "SA":4
}

只需遍历输入数组并从每个条目创建一个对象。

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