jquery - 从flat json创建嵌套的json

时间:2014-07-28 07:00:11

标签: javascript jquery json

以下是JSON数据。

JSON:

[{
    "Code":"US-AL",
    "Name":"Alabama",
    "Population":4833722
    },
    {
    "Code":"US-AK",
    "Name":"Alaska",
    "Population":735132
    },
    {
    "Code":"US-AZ",
    "Name":"Arizona",
    "Population":6626624
    },
    {
    "Code":"US-AR",
    "Name":"Arkansas",
    "Population":2959373
    },
    {
    "Code":"US-CA",
    "Name":"California",
    "Population":38332521
    },
    {
    "Code":"US-CO",
    "Name":"Colorado",
    "Population":5268367
    },
    {
    "Code":"US-CT",
    "Name":"Connecticut",
    "Population":3596080
}]

我想将该数据转换为此格式。

[{
    "US-AL": {
        "name" : "Alabama",
        "population" : 4833772
    },
    "US-AK": {
        "name" : "Alaska",
        "population" : 735132
    }
}]

我尝试使用此功能并将名称和人口分开。

var ParentData = [];
var ChildData = {"name": [], "population": []};

data.forEach(function(val, i) {

    ParentData.push(val.Code);
    ChildData.name.push(val.Name);
    ChildData.population.push(val.Population);

})

但我不是那个专家。只是一个学习者,我不知道如何推送到分别与它对齐的父数据。

任何帮助对我来说都非常有帮助。

提前致谢。

3 个答案:

答案 0 :(得分:1)

试试这个:

var newData = {};
data.forEach(function(val) {
    newData[val.Code] = {name: val.Name, population: val.Population};
});

请记住,IE8-本身并不支持forEach,尽管它可以是polyfilled。这适用于每个浏览器:

for (var i = 0; i < data.length; i++)
    newData[data[i].Code] = {name: data[i].Name, population: data[i].Population};

或者,因为你添加了&#34; jquery&#34;标签,你也可以使用:

$.each(data, function() {
    newData[this.Code] = {name: this.Name, population: this.Population};
});

答案 1 :(得分:0)

尝试使用javascript的原生map

var newData = data.map(function (obj) {
    var newObj = {};
    newObj[obj.Code] = {};
    newObj[obj.Code].name = obj.Name;
    newObj[obj.Code].population = obj.Population;
    return newObj;
});

console.log(newData)

答案 2 :(得分:0)

[{
   "US-AL":{
     "name":"Alabama",
     "population":4833722
   }
 },
 {
   "US-AK":{
     "name":"Alaska",
     "population":735132
   }
 },
 {
   "US-AZ":{
     "name":"Arizona",
     "population":6626624
   }
 },
 {
   "US-AR":{
     "name":"Arkansas",
     "population":2959373
   }
 },
 {
   "US-CA":{
     "name":"California",
     "population":38332521
   }
 },
 {
   "US-CO":{
     "name":"Colorado",
     "population":5268367
   }
 },
 {
   "US-CT":{
     "name":"Connecticut",
     "population":3596080
   }
 }
]

代码:

var newDatas = datas.map(function(item) {
    var obj = {};
    obj[item.Code] = { name: item.Name, population: item.Population };
    return obj;
});

datas是包含原始来源的数组。