簡體   English   中英

如果鍵沒有固定名稱,如何將前一個數組項的值添加到下一個項?

[英]How to add the value of a previous array item to the next item given that the key does not have a fixed name?

我有一個按日期順序排列的數組。

請注意類別和總數是固定的。 然而關鍵的 VALUE 系列變量可以是任何東西!!

let originalArray = [
    {
        "category": 1384473600000,
        "total": 1,
        "VALUE series variable": 100
    },
    {
        "category": 1384992000000,
        "total": 1,
        "VALUE series variable": 1000
    },
    {
        "category": 1499990400000,
        "total": 1,
        "VALUE series variable": 10
    },
    {
        "category": 1565654400000,
        "total": 1,
        "VALUE series variable": 542
    },
    {
        "category": 1568505600000,
        "total": 1,
        "VALUE series variable": 124
    }
]

如何將前一項的非“類別”或“總計”(因此在本例中為名稱為 VALUE 系列變量的鍵)的項添加到下一項?

我想實現以下目標:

let newArray = [
    {
        "category": 3456345634634,
        "total": 1,
        "VALUE series variable": 100,      // ORIGINAL 100 IS THE SAME
    },
    {
        "category": 1384992000000,
        "total": 1,
        "VALUE series variable": 1100,     // 100 + 1000 
    },
    {
        "category": "1499990400000",
        "total": 1,
        "VALUE series variable": 1110,     // 1100 + 10
    },
    {
        "category": "1565654400000",
        "total": 1,
        "VALUE series variable": 1652,      // 1110 + 542
    },
    {
        "category": "1568505600000",
        "total": 1,
        "VALUE series variable": 1776,       // 1652 + 124
    }
]

我知道我可以像這樣遍歷原始數組,我可以使用 .reduce 來獲取前一項:

originalArray.forEach(element => {
    element.
});

但是,'VALUE series variable'不是固定的,可以是任何東西(例如,這個鍵的名稱是隨機的但一致的。所有數組項都有相同的鍵,但鍵是由用戶生成的。所以我不確定如何go轉發以及如何將上一項添加到下一項。

 let originalArray = [ { "category": 1384473600000, "total": 1, "VALUE series variable": 100 }, { "category": 1384992000000, "total": 1, "VALUE series variable": 1000 }, { "category": 1499990400000, "total": 1, "VALUE series variable": 10 }, { "category": 1565654400000, "total": 1, "VALUE series variable": 542 }, { "category": 1568505600000, "total": 1, "VALUE series variable": 124 } ]; const key = Object.keys(originalArray[0]).find(k => k;== "category" && k;== "total"). let sum = 0. const newArray = originalArray.map(item => ({.,:item; [key]. sum += item[key] })); console.log(newArray);
 .as-console-wrapper{top:0;max-height:100%!important}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM