如何在JavaScript对象循环中递归聚合值?

问题描述 投票:1回答:1

我费时费力地试图创建一个JavaScript函数来遍历对象的每个键的值,并仅当对象键(它是一个时间戳)是或大于上一个键。

为了直观地解释这一点,我试图通过将前一天的每个值汇总到最近一天,来将下面的图(看起来看上去不太吸引人)翻到右上方。 >

enter image description here


试图旋转当前对象:
var orderedTimeSeriesObject = {
    1573538400: { // Tue, 12 Nov 2019 06:00:00
        clicks: 14,
        signups: 20
    },
    1574316000: { // Thu, 21 Nov 2019 06:00:00
        clicks: 13,
        signups: 15
    },
    1574488800: { // Sat, 23 Nov 2019 06:00:00
        clicks: 0,
        signups: 0
    }
};

进入此(目标):
var orderedTimeSeriesObject = {
    1573538400: { // Tue, 12 Nov 2019 06:00:00
        clicks: 14,
        signups: 20
    },
    1574316000: { // Thu, 21 Nov 2019 06:00:00
        clicks: 27,
        signups: 35
    },
    1574488800: { // Sat, 23 Nov 2019 06:00:00
        clicks: 27,
        signups: 35
    }
};


这是我当前的代码:

var newOrderedTimeSeriesObject = {};

Object.keys(orderedTimeSeriesObject).forEach((timestamp) => { 
    newOrderedTimeSeriesObject[timestamp] = {};
    Object.keys(orderedTimeSeriesObject).forEach((timestampToCompare) => { 
        if (timestamp >= timestampToCompare) {
            Object.values(timestamp).forEach((metric) => { 
                const metricAggregated = metric + timestampToCompare[metric];
                newOrderedTimeSeriesObject[timestamp][metric] = metricAggregated;
            });
        }
    });
});

console.log(newOrderedTimeSeriesObject);

我已经花了好几个小时不停地努力,在嵌套循环中迷路了,尝试递归时迷失了自己。我在这里有什么可以忽略的吗-甚至可能吗?任何指导或帮助将不胜感激。

更新:

感谢RK的回答,这是我最后得到的结果:

let lastKey = 0;
let lastValue = null;
for (key in orderedTimeSeriesObject)
{
    if (lastKey < key && lastValue != null)
    {
        Object.keys(orderedTimeSeriesObject[key]).forEach((metric) =>
        {
            orderedTimeSeriesObject[key][metric] += lastValue[metric];
        });
    }
    lastKey = key;
    lastValue = orderedTimeSeriesObject[key];
}

console.log(orderedTimeSeriesObject);

[我很难过,试图制作一个JavaScript函数来遍历对象的每个键的值并仅在...

javascript recursion chart.js
1个回答
2
投票
© www.soinside.com 2019 - 2024. All rights reserved.