转换两个JSON结构的更好方法

时间:2013-10-01 06:39:59

标签: javascript json

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

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

1 个答案:

答案 0 :(得分: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
  });
});