我有一个以这种格式返回指标数据的API:
[
{
"concept": "population",
"year": 2012,
"value": 9.5,
"country-name": "Sweden",
},
{
"concept": "education",
"year": 2012,
"value": 12,
"country-name": "Sweden",
},
{
"concept": "population",
"year": 2012,
"value": 5,
"country-name": "Norway",
},
{
"concept": "eduction",
"year": 2012,
"value": 12,
"country-name": "Norway",
}
]
基于此,我通常需要按国家和年份对此进行分组,以获得类似:
var data = [
{id : Sweden, population : 9.5, education: 12},
{id : Norway, population : 5, education: 12},
]
或者只是按国家/地区和年份值作为数组:
var data = [
{id : Sweden, values : [ { year : 2012, population : 9.5, education: 12 }, {...} ]},
{id : Norway, values : [ { year : 2012, population : 5, education: 12 }, {...} ]},
]
答案 0 :(得分:2)
你可以自己做,只需迭代并创建你需要的东西,比如
var data = [];
json.forEach(function(item) {
var country = item['country-name'],
match = false,
obj = {}
data.forEach(function(dataItem, i) {
if (dataItem.id === country) {
match = true;
obj = data[i];
}
});
obj.id = country;
obj[item.concept] = item.value;
if (!match) data.push(obj)
});
答案 1 :(得分:0)
您可能会发现一个对象比数组更容易使用:
var data = {};
indicatordata.forEach(function(item){
var country = item['country-name'];
var year = item.year;
data[country] = data[country] || {id: item['country-name'], values: {}};
var values = data[country].values;
values[year] = values[year] || {};
values[year][item.concept] = item.value;
});
答案 2 :(得分:-1)
您可以使用D3执行此操作。 d3.nest
和Array.prototype.reduce
具体而言。代码是声明性的,易于维护。
var rawData = [
{
"concept": "population",
"year": 2012,
"value": 9.5,
"country-name": "Sweden",
},
{
"concept": "education",
"year": 2012,
"value": 12,
"country-name": "Sweden",
},
{
"concept": "population",
"year": 2012,
"value": 5,
"country-name": "Norway",
},
{
"concept": "eduction",
"year": 2012,
"value": 12,
"country-name": "Norway",
}
];
var data = d3.nest()
.key(function(d)
{
return d['year'];
})
.key(function(d)
{
return d['country-name'];
})
.rollup(function(group)
{
return group.reduce(function(result, d)
{
result[d['concept']] = d['value'];
return result;
}, {});
})
.entries(rawData);
console.log(data);

<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
&#13;