像键和值一样创建json

时间:2013-03-26 06:22:15

标签: javascript underscore.js

var data1=[
    {"year":2000,
     "country":"Madagascar",
     "country_id":847,
     "indicator":"Current account balance - National Currency (millions)"
    },
    {"year":2005,
     "country":"Madagascar",
     "country_id":847,
     "indicator":"Current account balance - National Currency (millions)"
    },
    {"year":2000,
     "country":"Madagascar",
     "country_id":847,
     "indicator":"Net Income - National Currency (millions)"
    },
    {"year":2005,
     "country":"Madagascar",
     "country_id":847,
     "indicator":"Net Income - National Currency (millions)"
    }
]

这是我的json数据 我想使用underscorejs

这样做
{
  "key":"Madagascar"
  "values":[
    {"year":2000,
     "country":"Madagascar",
     "country_id":847,
     "indicator":"Current account balance - National Currency (millions)"
    },
    {"year":2005,
     "country":"Madagascar",
     "country_id":847,
     "indicator":"Current account balance - National Currency (millions)"
    }
  ]
}

请任何人都可以帮我解决这个问题 使用underscore.js

1 个答案:

答案 0 :(得分:0)

Underscore有一个_.groupBy()方法可以完成繁重的工作,但它会为每个值创建一个带有键的对象:

var groupedData1 = _.groupBy(data1, 'country');

这是groupedData1的值:

{"Madagascar": [
    {
        "year": 2000,
        "country": "Madagascar",
        "country_id": 847,
        "indicator": "Current account balance - National Currency (millions)"
    }, 
    {
        "year": 2005,
        "country": "Madagascar",
        "country_id": 847,
        "indicator": "Current account balance - National Currency (millions)"
    }, 
    {
        "year": 2000,
        "country": "Madagascar",
        "country_id": 847,
        "indicator": "Net Income - National Currency (millions)"
    }, 
    {
        "year": 2005,
        "country": "Madagascar",
        "country_id": 847,
        "indicator": "Net Income - National Currency (millions)"
    }
]}

要转换为键/值数组,可以使用_.each()和_.keys()遍历每个国家/地区:

var groupedData2 = [];

_.each(_.keys(groupedData1), function (country) {
    groupedData2.push({
        "key": country, 
        "values": groupedData1[country]
    });
});

这会创建一个对象数组,每个国家/地区都有一个对象:

[{
    "key": "Madagascar",
    "values": [{
        "year": 2000,
        "country": "Madagascar",
        "country_id": 847,
        "indicator": "Current account balance - National Currency (millions)"
    }, {
        "year": 2005,
        "country": "Madagascar",
        "country_id": 847,
        "indicator": "Current account balance - National Currency (millions)"
    }, {
        "year": 2000,
        "country": "Madagascar",
        "country_id": 847,
        "indicator": "Net Income - National Currency (millions)"
    }, {
        "year": 2005,
        "country": "Madagascar",
        "country_id": 847,
        "indicator": "Net Income - National Currency (millions)"
    }]
}]