簡體   English   中英

在對象數組內的對象內設置動態鍵的總和

[英]set sum of dynamic keys within an object inside an array of object

我有一個對象數組,看起來像這樣:-

const myObjArr = [
        {
            "channelName": "AFM",
            "21-Apr-2022": 2,
            "22-Apr-2022": 2,
            "27-Apr-2022": 1,
            "29-Apr-2022": 3,
            "19-Apr-2022": 1
        },
        {
            "channelName": "Organic Others",
            "6-Apr-2022": 6,
            "27-Apr-2022": 4,
            "7-Apr-2022": 3,
            "21-Apr-2022": 1,
            "8-Apr-2022": 1
        },
        {
            "channelName": "website",
            "27-Apr-2022": 1
        }
    ]

現在我想再添加一個鍵,該鍵在該數組的每個對象中命名為 total,它保存所有日期鍵的總和,以澄清我在下面的 reqArray 變量中提供所需的輸出

reqArray = [
        {
            "channelName": "AFM",
            "21-Apr-2022": 2,
            "22-Apr-2022": 2,
            "27-Apr-2022": 1,
            "29-Apr-2022": 3,
            "19-Apr-2022": 1,
            "total":9
        },
        {
            "channelName": "Organic Others",
            "6-Apr-2022": 6,
            "27-Apr-2022": 4,
            "7-Apr-2022": 3,
            "21-Apr-2022": 1,
            "8-Apr-2022": 1
            "total": 15
        },
        {
           "channelName": "website",
            "27-Apr-2022": 1,
            "total" : 1
        }
    ]
  function addFieldsForItem (arr = []) {
    arr.forEach(function(item) {
      let total = 0;
      Object.keys(item).forEach(function(key) {
        if (typeof item[key] === 'number') {
          total = total + item[key]
        }
      })
      item.total = total
    })
    return arr;
  }
  
  

暫無
暫無

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

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