0

我有以下 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;
    });
}

任何人都可以提出更清洁的方法吗?

4

1 回答 1

1

我不会称它为更清洁(基本上它在做同样的事情),但它只对整个数据迭代 1 次:

var yearMap = {};

$.each(data,function(k,v){
  $.each(v,function(kk,vv){
    if(!yearMap[vv.year])yearMap[vv.year]={};
    yearMap[vv.year][k]=vv.total
  });
});
于 2013-10-01T07:48:23.353 回答