gpt4 book ai didi

Javascript将对象数组累积到对象数组

转载 作者:数据小太阳 更新时间:2023-10-29 05:05:15 24 4
gpt4 key购买 nike

我有一个对象数组:

var myArray = [
{
"date" : "03/01/2017",
"value" : 2
}, {
"date" : "04/01/2017",
"value" : 6
}, {
"date" : "05/01/2017",
"value" : 4
}
];

我需要累加值并保持同一个数组更新值

结果是这样的

var myArray = [
{
"date" : "03/01/2017",
"value" : 2
}, {
"date" : "04/01/2017",
"value" : 8 //(2+6)
}, {
"date" : "05/01/2017",
"value" : 12 //(2+6+4)
}
];

我知道这是存在的

[0, 1, 2, 3, 4].reduce(function(accumulator, currentValue, currentIndex, array) {
return accumulator + currentValue;
});

但是我找不到对象也返回对象的例子

最佳答案

使用Array.prototype.forEachthis 参数来累积 - 请参见下面的演示:

var myArray=[{"date":"03/01/2017","value":2},{"date":"04/01/2017","value":6},{"date":"05/01/2017","value":4}];

myArray.forEach(function(e){
this.count = (this.count || 0) + e.value;
e.value = this.count;
},Object.create(null));

console.log(myArray);
.as-console-wrapper{top:0;max-height:100%!important;}

关于Javascript将对象数组累积到对象数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41467413/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com