2013-10-01 2 views
0

를 변환에 나는 다음과 같은 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; 
    }); 
} 

누구나 더 깨끗한 접근법을 제시 할 수 있습니까?

+4

이 질문은 오프 토픽으로 나타납니다 해결되다. http://codereview.stackexchange.com/ – Quentin

+0

첫 번째 해결책은 무엇이 문제입니까? – freakish

답변

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 
    }); 
});