2013-07-12 5 views
0

자바 스크립트 객체가 있습니다.이 객체는 json을 통해 데이터베이스에서 가져옵니다. 같은 달을 기준으로 가치를 계산하는 쉬운 방법이 있습니까? (색깔은 중요하지 않다). 그래서 결과는 다음과 같이 될 것입니다 :자바 스크립트 객체의 개수 속성 값을 계산합니다.

data = [ 
{ 
    "value": 30, 
    "month": 8, 
    "color": "#49e630" 
}, 
{ 
    "value": 50, 
    "month": 7, 
    "color": "#5001dc" 
}, 
{ 
    "value": 100, 
    "month": 7, 
    "color": "#6365c3" 
} 
] 

result = [ 
{ 
    "value": 30, 
    "month": 8, 
    "color": "#49e630" 
}, 
{ 
    "value": 150, 
    "month": 7, 
    "color": "#6365c3" 
} 
] 

답변

0

과 같이, 월 값을 기준으로지도를 만드는 방법에 대해 어떻게 :

//populate a map with keys based on the month 
var monthMap = new Object(); 
for (var i = 0; i < data.length; i++) { 
    if (monthMap[data[i]['month']] == null) { 
     monthMap[data[i]['month']] = data[i]; 
    } else { 
     monthMap[data[i]['month']]['value'] += data[i]['value']; 
    } 
} 

//convert monthMap to list 
var result = []; 
for (var key in monthMap) { 
    if (monthMap.hasOwnProperty(key)) { 
     result.push(monthMap[key]); 
    } 
} 

편집 : 당신은 또한이 같은 데이터 루프를 쓸 수있는 약간 더 읽기 쉬울 수도 있습니다 :

//populate a map with keys based on the month 
var monthMap = new Object(); 
data.forEach(function(listitem) { 

    var month = listitem['month']; 

    if (monthMap[month] == null) { 
     monthMap[month] = listitem; 
    } else { 
     monthMap[month]['value'] += listitem['value']; 
    } 
}); 

//convert to list... 
+0

감사합니다. 완벽하게 작동합니다. – Lukaydo

+0

도와 줘서 기쁩니다! 기회가 생겼을 때이 대답을 받아 들일 수 있으면 감사하겠습니다. 감사! – user1171848

관련 문제