先貼代碼
function groupBy(list,key){
return list.reduce((rv,current)=>{
(rv[current[key]]=rv[current[key]]||[]).push(current)
return rv
},{})
}
舉例
let list=[
{ Phase: "Phase 1", Step: "Step 1", Task: "Task 1", Value: "5" },
{ Phase: "Phase 1", Step: "Step 1", Task: "Task 2", Value: "10" },
{ Phase: "Phase 1", Step: "Step 2", Task: "Task 1", Value: "15" },
{ Phase: "Phase 1", Step: "Step 2", Task: "Task 2", Value: "20" },
{ Phase: "Phase 2", Step: "Step 1", Task: "Task 1", Value: "25" },
{ Phase: "Phase 2", Step: "Step 1", Task: "Task 2", Value: "30" },
{ Phase: "Phase 2", Step: "Step 2", Task: "Task 1", Value: "35" },
{ Phase: "Phase 2", Step: "Step 2", Task: "Task 2", Value: "40" }
]
groupBy(list,'Phase')
返回結(jié)果
{
"Phase 1": [
{
"Phase": "Phase 1",
"Step": "Step 1",
"Task": "Task 1",
"Value": "5"
},
{
"Phase": "Phase 1",
"Step": "Step 1",
"Task": "Task 2",
"Value": "10"
},
{
"Phase": "Phase 1",
"Step": "Step 2",
"Task": "Task 1",
"Value": "15"
},
{
"Phase": "Phase 1",
"Step": "Step 2",
"Task": "Task 2",
"Value": "20"
}
],
"Phase 2": [
{
"Phase": "Phase 2",
"Step": "Step 1",
"Task": "Task 1",
"Value": "25"
},
{
"Phase": "Phase 2",
"Step": "Step 1",
"Task": "Task 2",
"Value": "30"
},
{
"Phase": "Phase 2",
"Step": "Step 2",
"Task": "Task 1",
"Value": "35"
},
{
"Phase": "Phase 2",
"Step": "Step 2",
"Task": "Task 2",
"Value": "40"
}
]
}