0

I have the following data structure

{
  metadata: {
    a: 0,
    b: 4,
    c: 1,
    d: 6
  }
}

I want to find a simple way to add all the variables in the metadata together without having to do them one at a time.. like metadata.a + metadata.b + metadata.c + metadata.d

I am hoping for a way to just add whatever variable exists in that

Any suggestions?

jaekie
  • 2,283
  • 4
  • 30
  • 52

2 Answers2

1

Simplified using ES6

const data = {
  metadata: {
    a: 0,
    b: 4,
    c: 1,
    d: 6
  }
}
const sum = Object.entries(data.metadata).reduce((sum, x) => sum+ x[1], 0)
console.log(sum)
xdeepakv
  • 7,835
  • 2
  • 22
  • 32
0

You can use a simple for ... in loop for that

const metadata = {
  a: 0,
  b: 4,
  c: 1,
  d: 6
}

let sum = 0

for (let key in metadata) {
  sum += metadata[key]
}
console.log(sum)
Ado
  • 637
  • 1
  • 6
  • 17