javascript - 按对象数组中的元素分组

时间:2017-04-04 19:06:37

标签: javascript typescript arraylist

我的数组是这样的:

Array= [
  {phase: "one", weight: "10"},
  {phase: "one", weight: "20"},
  {phase: "two", weight: "30"},
  {phase: "two", weight: "40"}
]

基本上在结果​​中,我想计算每个对象在相应阶段的重量百分比。例如,第一个对象权重百分比为20/(20 + 40) * 100 = 0.333,因为它属于第一阶段。

结果应该是这样的。

Array= [
  {phase: "one", weight: "20", percentage:"0.333"},
  {phase: "one", weight: "40", percentage:"0.666"},
  {phase: "two", weight: "30", percentage:"0.3"},
  {phase: "two", weight: "70", percentage:"0.7"}
]

1 个答案:

答案 0 :(得分:0)

首先创建阶段和权重的字典,以便您可以找到特定阶段的所有权重的总和。然后遍历阶段对象以设置百分比。

const phases = [
  { phase: "one", weight: 10 },
  { phase: "one", weight: 20 },
  { phase: "two", weight: 30 },
  { phase: "two", weight: 40 }
];

const phaseWeights = phases.reduce(
  (dict, {phase, weight}) => {
    dict[phase] = (dict[phase] || 0) + weight;
    return dict;
  },
  Object.create(null)
);

phases.forEach((phaseObj) => {
  const {phase, weight} = phaseObj;
  phaseObj.percentage = weight / phaseWeights[phase] * 100;
});

console.log(phases);