简体   繁体   中英

Sum values of a JavaScript object

Given an Object of this structure

{
    "1": {
        "data": {
            "a": 100,
            "z": 100,
            "e": 50
        },
        "percentage": {
            "a": 10,
            "z": 10,
            "e": 41.09
        }
    },
    "2": {
        "data": {
            "a": 10,
            "z": 10,
            "e": 20
        },
        "percentage": {
            "a": 30,
            "z": 40,
            "e": 50
        }
    }
}

i want to sum the values of this object in order to get this similar structure

{
    "data": {
        "a": sum(a),
        "z": sum(z),
        "e": sum(e)
    },
    "percentage": {
        "a": sum(a)/numberOfelements,
        "z": sum(z)/numberOfelements,
        "e": sum(e)/numberOfelements
    }
}

As am just started learnig js i find it hard to implement the sum inside this map

Object.keys(filtered).map(key => ({
        data: data[key].data,
        percentage: data[key].percentage,
      }))

any help would be appriciated

If numOfElemements meant elements in data object, then current implementation will do. Else uncomment the existing commented lines, and comment the line after the last commented line. Which considers elements in the data object.

 const obj = { 1: { data: { a: 100, z: 100, e: 50, }, }, 2: { data: { a: 10, z: 10, e: 20, }, }, }; function groupBySum(obj) { let data = {}; let percentage = {}; // let numberOfElements = 0; for (let i in obj) { // numberOfElements += 1; for (let j in obj[i].data) { if (data[j] === undefined) { data[j] = obj[i].data[j]; } else { data[j] += obj[i].data[j]; } } } for (let i in data) { // percentage[i] = data[i] / numberOfElements; percentage[i] = data[i] / Object.keys(data).length; } return { data, percentage, }; } console.log(groupBySum(obj));

Also it'll be a good idea to change your current structure to array format as below.

const obj = [
  {
    data: {
      a: 100,
      z: 100,
      e: 50,
    },
    percentage: {
      a: 10,
      z: 10,
      e: 41.09,
    },
  },
  {
    data: {
      a: 10,
      z: 10,
      e: 20,
    },
    percentage: {
      a: 30,
      z: 40,
      e: 50,
    },
  },
];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM