I am facing a challenge with an object that has changeable keys, which I do not want to rely on. The keys in this object are not fixed. Here is an example:
interface Inf {
[key: string]: number
}
const obj: Inf = {
'2020-01-01': 4,
'2020-01-02': 5,
}
const obj2: Inf = {
'2020-01-05': 10,
'2020-02-10': 15,
}
const finalObj = { one: obj, two: obj2, ... }
My goal is to calculate the sum of 10 + 15 + 4 + 5 regardless of their key names. I have lodash installed, which offers a method called sumBy
. However, it requires input as an array, while mine is a full object.
Is there a way to achieve a total of 34
from this object efficiently? What would be the best approach for handling such an operation?
let x = 0
Object.values(obj).forEach(o => {
x += o
})
While the above solution works, I'm curious if there is a better or more concise way to accomplish this task. Any suggestions for a shorter and faster implementation?