My JSON looks something like this:
const json = {
"08/23/2022": {
"One": 254,
"Two": 92,
"Three": 8
},
"08/13/2022": {
"One": 327,
"Two": 86,
},
"08/14/2022": {
"One": 431
},
}
I need to add all of these values, regardless of what the key is. In this case, the calculation would be 254 92 8 327 86 431, and the output would be 1198. Previously I had just been counting the first ([0]) value but I just realized that's not correct and the only solution I can think of is essentially nesting loops, but that doesn't seem like the cleanest or most efficient way to accomplish this. This is my current code for reference:
for (const [key, value] of Object.entries(json)) {
Object.entries(value).forEach(val => output = val[1])
}
So what's the correct way?
CodePudding user response:
There are fundamentally two dimensions to go through - the date-object pairs of the top level object, and then the digit-number pairs of the inner objects. So there really isn't any decent way around logic that accounts for two levels of nesting.
But, a better approach would be to use Object.values
- you don't care about the keys, only the values.
const json = {
"08/23/2022": {
"One": 254,
"Two": 92,
"Three": 8
},
"08/13/2022": {
"One": 327,
"Two": 86,
},
"08/14/2022": {
"One": 431
},
};
const sum = Object.values(json)
.flatMap(Object.values)
.reduce((a, b) => a b, 0);
console.log(sum);
The result is 1198 because that's the result of 254 92 8 327 86 431.
Well, I suppose there's a way around using an Object or object iteration method twice (or more) - JSON.stringify
will iterate over all nested properties anywhere - but that's silly and shouldn't be used in real code.
const json = {
"08/23/2022": {
"One": 254,
"Two": 92,
"Three": 8
},
"08/13/2022": {
"One": 327,
"Two": 86,
},
"08/14/2022": {
"One": 431
},
};
let sum = 0;;
JSON.stringify(json, (_, val) => {
if (typeof val === 'number') sum = val;
return val;
});
console.log(sum);