2017-01-16 43 views
-2

例如陣列:Array對象的,總和鍵但關鍵是未知

var arr = [ 
{ 
    Test 0: 142.0465973851827, 
    Test 1: 199, 
    timestamp: "2017-01-16T00:00:00.000Z" 
}, 
{ 
    Test 0: 142.0465973851827, 
    Test 1: 199, 
    timestamp: "2017-01-17T00:00:00.000Z" 
} 
] 

Test 0Test 1可以是任何東西。我試圖返回這樣的結果:

var arr = [ 
{ 
    total: 341, 
    timestamp: '2017-01-16T00:00:00.000Z' 
}, 
{ 
    total: 341, 
    timestamp: '2017-01-17T00:00:00.000' 
} 
] 

什麼是適當的循環類型來做到這一點?

+0

是否有任何邏輯在結果 「*總:341 *」 來計算。它是所有Test0 + Test1的總和嗎? –

+0

@AlaEddineJEBALI它是除時間戳以外的所有東西的總和。 –

+0

看到我的答案,如果它可以幫助你。你可以在* sum *變量之前檢查* exclude *一個元素數組來排斥並使用* if(exclude.indexOf(key)=== -1)* –

回答

0

可以映射在陣列上,然後運行減少每個對象的Object.keys,不含timestamp屬性

var arr = [{ 
 
    Test0: 142.0465973851827, 
 
    Test1: 199, 
 
    timestamp: "2017-01-16T00:00:00.000Z" 
 
}, { 
 
    Test0: 142.0465973851827, 
 
    Test1: 199, 
 
    timestamp: "2017-01-17T00:00:00.000Z" 
 
}] 
 

 
var res = arr.map(v => ({ 
 
    total: Object.keys(v).reduce((a, b) => b !== 'timestamp' ? a + v[b] : a, 0), 
 
    timestamp: v.timestamp  
 
})); 
 

 
console.log(res);

0

array.map,Object.keys,array.filterarray.reduce的組合可以做到這一點。使用array.map運行數組Object.keys以獲取每個對象的鍵和array.filter只抓取以「Test」開頭的鍵,然後使用array.reduce累積結果。

以上所有內容都可以使用簡單循環輕鬆完成。數組方法可以使用常規的for循環來完成,而Object.keys將需要使用object.hasOwnProperty守護的for-in

0
arr=arr.map(el=>{return el.total=Object.keys(el).filter(key=>key.split("Test")[1]).reduce((total,key)=>total+el[key],0),el;}); 

它確實是在他的答案的第一部分描述的夢想家約瑟夫。

+0

請編輯你的答案,否則你可能會被低估。現在,它只是一個沒有上下文的建議。請看這裏[如何寫出一個好答案](http://stackoverflow.com/help/how-to-answer)。 – jacefarm

0

這是怎麼回事?

var arr = [ 
 
{ 
 
    Test0: 142.0465973851827, 
 
    Test1: 199, 
 
    timestamp: "2017-01-16T00:00:00.000Z" 
 
}, 
 
{ 
 
    Test0: 142.0465973851827, 
 
    Test1: 199, 
 
    timestamp: "2017-01-17T00:00:00.000Z" 
 
} 
 
]; 
 

 
var result = []; 
 
var exclude = "timestamp"; 
 
arr.forEach(function(elements){ 
 
\t var sum = 0; 
 
\t for(key in elements){ 
 
\t \t if(key !== exclude){ 
 
\t \t \t sum += elements[key]; 
 
\t \t } 
 
\t } 
 
\t var newElement = {total: sum.toFixed(2), timestamp: elements.timestamp} 
 
\t result.push(newElement); 
 
}); 
 

 
console.info(result);