例如数组:
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 0
和Test 1
可以是任何内容。我试着回复这样的结果:
var arr = [
{
total: 341,
timestamp: '2017-01-16T00:00:00.000Z'
},
{
total: 341,
timestamp: '2017-01-17T00:00:00.000'
}
]
这样做的正确循环类型是什么?
答案 0 :(得分:0)
array.map
,Object.keys
,array.filter
和array.reduce
的组合可以做到这一点。使用array.map
运行数组Object.keys
以获取每个对象的键,array.filter
仅获取以" Test"开头的键,然后使用累积结果array.reduce
。
上述所有内容也可以使用简单的循环轻松完成。数组方法可以使用常规for
循环完成,而Object.keys
则需要for-in
守护object.hasOwnProperty
。
答案 1 :(得分: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;});
它完全与他的回答的第一部分中描述的梦想家约瑟夫完全相同。
答案 2 :(得分:0)
您可以映射数组,然后在每个对象的Object.keys上运行reduce,不包括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);
答案 3 :(得分:0)
function number(v){ return +v || 0; }
arr.map(function(obj){
var timestamp = obj.timestamp;
var total = Object.keys(obj)
.reduce(function(sum, key){
return sum + number( obj[key] );
}, 0);
return { total, timestamp }
})
答案 4 :(得分: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){
var sum = 0;
for(key in elements){
if(key !== exclude){
sum += elements[key];
}
}
var newElement = {total: sum.toFixed(2), timestamp: elements.timestamp}
result.push(newElement);
});
console.info(result);