我有以下 JSON:
{
"Foo": [{"total": 2000, year: 1}, {"total": 3400, year: 2}, {"total": 5000, year: 3}],
"Bar": [{"total": 1000, year: 1}, {"total": 2400, year: 2}, {"total": 7000, year: 3}],
}
我需要它的形式:
[
{ "Foo": 2000, "Bar": 1000, year: 1},
{ "Foo": 3400, "Bar": 2400, year: 2},
{ "Foo": 5000, "Bar": 7000, year: 3}
]
我们能想到的最好的办法是坦率地说很尴尬:
var yearMap = {};
// Initialising the map of years eg. {1: { } , 2: {} .. }
for (var key in data) {
var foos = data[key];
$(foos).each(function(index, val) {
yearMap[val.year] = { };
});
}
// Iterates through the data and just puts the commission total against the year
for (var key in data) {
var foos = data[key];
$(foos).each(function(index, val) {
yearMap[val.year][key] = val.total.value;
});
}
任何人都可以提出更清洁的方法吗?