计算总价值并使用该总价值获得每个百分比的价值

时间:2019-09-10 12:02:03

标签: javascript

我正在尝试获取每个值的百分比。 输入:

ShowList = [{
        age: {
            age_55_above: 285737,
            age_25_34: 12217710,
            age_unspecified: 655187,
            age_18_24: 9035930,
            age_45_54: 927554,
            …
        }
        gender: {
            male: 12467636,
            unspecified: 11872,
            female: 17833279
        }
    },
    {
        age: {
            age_55_above: 285237,
            age_25_34: 12227710,
            age_unspecified: 651187,
            age_18_24: 9135930,
            age_45_54: 9227554,
            …
        }
        gender: {
            male: 111467636,
            unspecified: 13872,
            female: 178344279
        }
    }
]
  1. 添加年龄总计285737 + 12217710 + 655187 + 9035930 + 927554和性别12467636 + 11872 + 17833279。
  2. 获得总计的百分比之后。即(285737 /总价// 23122118)* 100
  3. 输出可以具有相同的json格式:
[{
        age: {
            age_55_above: % val,
            age_25_34:  % val,
            age_unspecified:  % val,
            age_18_24:  % val,
            age_45_54:  % val,
            …
        }
        gender: {
            male:  % val,
            unspecified:  % val,
            female:  % val
        }
    },
    {
        age: {
            age_55_above:  % val,
            age_25_34:  % val,
            age_unspecified:  % val,
            age_18_24:  % val,
            age_45_54:  % val,
            …
        }
        gender: {
            male:  % val,
            unspecified:  % val,
            female:  % val
        }
    }
]

我尝试过的方法: 首先,我尝试获取总计,然后从每个值中取出百分比。欢迎任何解决方案。

for (var key in this.ShowsList) {
          for (var keyGender in this.ShowsList[key]) {
              total[key] = {};
              for (var keyVal in this.ShowsList[key][keyGender]) {
                total[key] = total[key] || {};
                total[key]["gender"] = total[key]["gender"] || 0;
                total[key]["age"] = total[key]["age"] || 0;
                if(this.ShowsList[key]["gender"][keyVal] != undefined){
                  total[key]["gender"] += this.ShowsList[key]["gender"][keyVal];
                }
                if(this.ShowsList[key]["age"][keyVal] != undefined){
                  total[key]["age"] += this.ShowsList[key]["age"][keyVal];
                }
                Obj[key] = Obj[key] || {};
                Obj[key][keyGender] = Obj[key][keyGender] || {};
                Obj[key][keyGender][keyVal] = Obj[key][keyGender][keyVal] || 0;
                // Logic to calculate percentage

                // Obj[key]["gender"][keyVal] = ((this.ShowsList[key]["gender"][keyVal]/ total[key]["gender"]) * 100);
// Obj[key]["age"][keyVal] = ((this.ShowsList[key]["age"][keyVal]/ total[key]["gender"]) * 100);

              }
          }
        }

3 个答案:

答案 0 :(得分:3)

您可以采用完整的动态方法,并通过添加项目并返回零件来获得百分比值。

function getPercent(object) {
    var entries = Object.entries(object),
        sum = entries.reduce((s, { 1: v }) => s + v, 0);

    return Object.assign({}, ...entries.map(([k, v]) => ({ [k]: v * 100 / sum })));
}

var data = [{ age: { age_55_above: 285737, age_25_34: 12217710, age_unspecified: 655187, age_18_24: 9035930, age_45_54: 927554 }, gender: { male: 12467636, unspecified: 11872, female: 17833279 } }, { age: { age_55_above: 285237, age_25_34: 12227710, age_unspecified: 651187, age_18_24: 9135930, age_45_54: 9227554 }, gender: { male: 111467636, unspecified: 13872, female: 178344279 } }],
    result = data.map(o => Object.assign(
        {},
        ...Object.entries(o).map(([k, v]) => ({ [k]: getPercent(v) }))
    ));

   console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

答案 1 :(得分:1)

由于ShowList内部对象将始终具有相同的结构,因此可以使用下面的代码。 (如果由于某种原因需要扩展性或更改属性,那么Nina Scholz的答案可能更合适)

首先,开始遍历ShowList,获取每个对象。
然后,通过使用age,创建一个仅包含每个对象的genderObject.values()值的数组。
使用.reduce对所有这些值求和,得出年龄和性别的总和。
现在,循环agegender对象的每个属性并进行计算以获得%

let ShowList = [{
        age: {
            age_55_above: 285737,
            age_25_34: 12217710,
            age_unspecified: 655187,
            age_18_24: 9035930,
            age_45_54: 927554            
        },
        gender: {
            male: 12467636,
            unspecified: 11872,
            female: 17833279
        }
    },
    {
        age: {
            age_55_above: 285237,
            age_25_34: 12227710,
            age_unspecified: 651187,
            age_18_24: 9135930,
            age_45_54: 9227554,            
        },
        gender: {
            male: 111467636,
            unspecified: 13872,
            female: 178344279
        }
    }
]

var results = []

for (var i = 0; i < ShowList.length; i++){
  let currentObj = ShowList[i];
  
  let ageValues = Array.from(Object.values(currentObj.age))
  let genderValues = Array.from(Object.values(currentObj.gender))
  
  let totalAges = ageValues.reduce((a,b) => a + b, 0)
  let totalGender = genderValues.reduce((a,b) => a + b, 0)
  
  let newObj = {age: {}, gender: {}}
  
  for (let key in currentObj.age){
    newObj.age[key] = (currentObj.age[key] / totalAges) * 100 + " %"
  }
  
  for (let key in currentObj.gender){
    newObj.gender[key] = (currentObj.gender[key] / totalGender) * 100 + " %"
  }
  
  results.push(newObj)
}

console.log(results)

答案 2 :(得分:1)

在这里看看:-

let ShowList = [
  {
    "age": {
      "age_55_above": 285737,
      "age_25_34": 12217710,
      "age_unspecified": 655187,
      "age_18_24": 9035930,
      "age_45_54": 927554
    },
    "gender": {
      "male": 12467636,
      "unspecified": 11872,
      "female": 17833279
    }
  },
  {
    "age": {
      "age_55_above": 285237,
      "age_25_34": 12227710,
      "age_unspecified": 651187,
      "age_18_24": 9135930,
      "age_45_54": 9227554
    },
    "gender": {
      "male": 111467636,
      "unspecified": 13872,
      "female": 178344279
    }
  }
]

let result = ShowList.map(function(item){
        let o = {};
        for(let key in item){// top level iteration
          o[key] = {}
          let sum = Object.keys(item[key]).reduce((a,b)=> a+item[key][b], 0) 
          for(let subkey in item[key]){// sub level iteration
            o[key][subkey] = (item[key][subkey]/sum)*100;
          }
        }
        return o;
      })


console.log(result)