我想从嵌套数组对象中获取不同的studentId和classNo。
Const arr = [
{
"studentId": 70,
"data": [
{
"studentId": 70,
"teacher": "Syam",
"classNo": 100,
},
{
"studentId": 70,
"teacher": "Mathew",
"classNo": 101,
},
]
},
{
"studentId": 69,
"data": [
{
"studentId": 69,
"teacher": "Sam",
"classNo": 102,
},
{
"studentId": 69,
"teacher": "Chris",
"classNo": 101,
},
]
}
]
我想根据studentId填充唯一的classNo数组的结果...
expecting like this..
[
70: [100, 101],
60: [102, 101]
]
OR
[
{studentId: 70, classNo: [100, 101]},
{studentId: 60, classNo: [102, 101]}
]
I have tried below code and not getting the required result.
arr.map((dt) => dt.data.map((item)=> item.studentId).filter((item, i, arr) => arr.indexOf(item) === i))
请任何人帮助我解决这个问题。
用reduce方法解决
arr.reduce((a,i)=>{
let t = i.data.map(x=>x.classNo).filter(x=>x!=='');
if(a[i.studentId]){
a[i.studentId] = [...t,...a[i.studentId]]
} else {
a[i.studentId] = [...t]
}
a[i.studentId] = [...new Set(a[i.studentId])]
return a;
},{})