Home > Blockchain >  How to do the sum of the values in an object
How to do the sum of the values in an object

Time:07-05

//What I'm trying to do is count the sum of the data in this array.

const storage = [
  { data: '1', status: '0' },
  { data: '2', status: '0' },
  { data: '3', status: '0' },
  { data: '4', status: '0' },
  { data: '5', status: '0' },
  { data: '6', status: '0' },
  { data: '7', status: '1' },
];

CodePudding user response:

You can use the reduce here, see more info about reduce

const storage = [{
    data: '1',
    status: '0'
  },
  {
    data: '2',
    status: '0'
  },
  {
    data: '3',
    status: '0'
  },
  {
    data: '4',
    status: '0'
  },
  {
    data: '5',
    status: '0'
  },
  {
    data: '6',
    status: '0'
  },
  {
    data: '7',
    status: '1'
  },
];


const sum = storage.reduce((acc, value) => acc   Number(value.data), 0);

console.log(sum)

CodePudding user response:

Just use a simple loop - no need to get snarled up with reduce.

(Just make sure you coerce the string value to a Number when you're doing the addition.)

const storage=[{data:"1",status:"0"},{data:"2",status:"0"},{data:"3",status:"0"},{data:"4",status:"0"},{data:"5",status:"0"},{data:"6",status:"0"},{data:"7",status:"1"}];

let sum = 0;

for (const obj of storage) {
  sum  = Number(obj.data);
}

console.log(sum);

CodePudding user response:

Something like this?

const total = storage.map(({data}) => Number(data)).reduce((a,b) => a   b, 0)

So, first, lets get an array of numbers, which is de first part:

storage.map(({data}) => Number(data)) 

This will get the data by destructuring from each of the elements, or you can write it like so:

storage.map((item) => Number(item.data))

Then we'll reduce the list by adding all the items together:

list.reduce((a,b) => a   b, 0)

This means, start with 0, then foreach element, add it to the result. This will give you the total.

  • Related