'set sum of dynamic keys within an object inside an array of object
I have one array of object which looks something like this:-
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
}
]
now I want to add one more key, which is named as total in each object of this array which hold sum of all date keys to clarify I am providing the required output in the reqArray variable below
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
}
]
Solution 1:[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;
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
