2016-12-05 46 views
-4

我有對象的數組JavaScript的分組陣列

[{ 
    quesName: 'ques1', 
    ans: 'ans1', 
    sectionName: 'section1' 
}, { 
    quesName: 'ques2', 
    ans: 'ans2', 
    sectionName: 'section1' 
}, { 
    quesName: 'ques3', 
    ans: 'ans3', 
    sectionName: 'section2' 
}, { 
    quesName: 'ques4', 
    ans: 'ans4', 
    sectionName: 'section2' 
}, { 
    quesName: 'ques5', 
    ans: 'ans5', 
    sectionName: 'section3' 
}, { 
    quesName: 'ques6', 
    ans: 'ans6', 
    sectionName: 'section3' 
}] 

我想組到這些物體一樣,

[{ 
    sectionName: "section1", 
    sectionValues: [{ 
    quesName: 'ques1', 
    ans: 'ans1' 
    }, { 
    quesName: 'ques2', 
    ans: 'ans2' 
    }] 
}, { 
    sectionName: "section2", 
    sectionValues: [{ 
    quesName: 'ques3', 
    ans: 'ans3' 
    }, { 
    quesName: 'ques4', 
    ans: 'ans4' 
    }] 
}, { 
    sectionName: "section2", 
    sectionValues: [{ 
    quesName: 'ques5', 
    ans: 'ans5' 
    }, { 
    quesName: 'ques6', 
    ans: 'ans6' 
    }] 
}] 
+5

你搞什麼名堂嘗試 – Sankar

+0

這將幫助:http://stackoverflow.com/questions/14446511/what-is-the-most-efficient-method-to-groupby-on-a-javascript-array對象 – Rajesh

+0

我嘗試通過手動迭代數組和分組。但是地圖功能是一個不錯的選擇 –

回答

1

你需要的是Array.map

const data = [{   
 
    quesName: 'ques1', 
 
    ans: 'ans1', 
 
    sectionName: 'section1' 
 
    }, { 
 
    quesName: 'ques2', 
 
    ans: 'ans2', 
 
    sectionName: 'section1' 
 
    }] 
 

 
const newData = data.map(
 
    ({ sectionName, ans, quesName }) => ({ 
 
    sectionName, 
 
    data: { 
 
     ans, 
 
     quesName 
 
     } 
 
    })) 
 

 
console.log(data, newData)