如何在javascript数组(nodejs)中按(多个键)和属性值之和进行分组

kb5ga3dv  于 2021-10-10  发布在  Java
关注(0)|答案(1)|浏览(228)

关闭。这个问题需要详细或明确。它目前不接受答案。
**想改进这个问题吗?**编辑这篇文章,添加细节并澄清问题。

14小时前关门了。
改进这个问题

[
    { Phase: "Phase 1", Step: "Step 1", Value1: "15" },
    { Phase: "Phase 1", Step: "Step 2", Value1: "20" },
    { Phase: "Phase 2", Step: "Step 1", Value1: "25" },
    { Phase: "Phase 2", Step: "Step 2", Value1: "30" },
    { Phase: "Phase 1", Step: "Step 1", Value1: "35" },
    { Phase: "Phase 1", Step: "Step 2", Value1: "40" },
    { Phase: "Phase 2", Step: "Step 1", Value1: "45" },
    { Phase: "Phase 2", Step: "Step 2", Value1: "50" }
]
[
    { Phase: "Phase 1", Step: "Step 1", Value1: "50" },
    { Phase: "Phase 1", Step: "Step 2", Value1: "60" },
    { Phase: "Phase 2", Step: "Step 1", Value1: "70" },
    { Phase: "Phase 2", Step: "Step 2", Value1: "80" }
]
bpsygsoo

bpsygsoo1#

您可以使用map来实现这一点。

var arr = [ {Phase: "Phase 1", Step: "Step 1", Value1: "15"},{Phase: "Phase 1", Step: "Step 2", Value1: "20"},{Phase: "Phase 2", Step: "Step 1", Value1: "25"},{Phase: "Phase 2", Step: "Step 2", Value1: "30"},{Phase: "Phase 1", Step: "Step 1", Value1: "35"},{Phase: "Phase 1", Step: "Step 2", Value1: "40"},{Phase: "Phase 2", Step: "Step 1", Value1: "45"}, {Phase: "Phase 2", Step: "Step 2", Value1: "50"}];

    var groupByPhaseAndStep = new Map();

    for(const jObj of arr){
      const {Phase, Step, Value1='0'} = jObj;
      var key = Phase + '~~'+ Step;
      var val = eval(Value1);
      if(groupByPhaseAndStep.has(key)){
        val+=groupByPhaseAndStep.get(key);
      }
      groupByPhaseAndStep.set(key, val);
    }

    var outputArr = [];
    groupByPhaseAndStep.forEach(function(val, key){

      outputArr.push({
        Phase: key.split('~~')[0],
        Step: key.split('~~')[1],
        Value1: val
      });
    });

    console.log(outputArr);

相关问题