Home > Mobile >  how to solve the merge mysql tables to getting json data from express api to transform data into sut
how to solve the merge mysql tables to getting json data from express api to transform data into sut

Time:11-30

getting the response from express api how can change the array data like this thanks in advance help me !

input = [
    { secId: "12", stuName: "aaa", stuGrade: "A", stuTotal: 100 },
    { secId: "12", stuName: "bbb", stuGrade: "A ", stuTotal: 98 },
    { secId: "13", stuName: "ccc", stuGrade: "B", stuTotal: 95 },
    { secId: "13", stuName: "ddd", stuGrade: "A", stuTotal: 70 },
  ];
output = [
    {
      secId: 12,
      stuDetails: [
        { stuName: "aaa", stuGrade: "A", stuTotal: 100 },
        { stuName: "bbb", stuGrade: "A ", stuTotal: 98 },
      ],
    },
    {
      secId: 13,
      stuDetails: [
        { stuName: "ccc", stuGrade: "B", stuTotal: 95 },
        { stuName: "ddd", stuGrade: "A", stuTotal: 70 },
      ],
    },
  ];

CodePudding user response:

use reduce

const input = [
    { secId: "12", stuName: "aaa", stuGrade: "A", stuTotal: 100 },
    { secId: "12", stuName: "bbb", stuGrade: "A ", stuTotal: 98 },
    { secId: "13", stuName: "ccc", stuGrade: "B", stuTotal: 95 },
    { secId: "13", stuName: "ddd", stuGrade: "A", stuTotal: 70 },
  ];
  
  
  const result = input.reduce((acc,item) => {
    const existingInput = acc.find(i => i.secId === item.secId)
    
    if(existingInput){
      existingInput.stuDetails.push({stuName: item.stuName, stuGrade: item.stuGrade, stuTotal: item.tuTotal })
      
    }
    else{
      acc.push({secId: item.secId, stuDetails: [{stuName: item.stuName, stuGrade: item.stuGrade, stuTotal: item.tuTotal }]})
      
   
    }
    
      return acc
   
  }, [])
  
  console.log(result)

CodePudding user response:

We can do it via Array.reduce()

let input = [
    { secId: "12", stuName: "aaa", stuGrade: "A", stuTotal: 100 },
    { secId: "12", stuName: "bbb", stuGrade: "A ", stuTotal: 98 },
    { secId: "13", stuName: "ccc", stuGrade: "B", stuTotal: 95 },
    { secId: "13", stuName: "ddd", stuGrade: "A", stuTotal: 70 },
  ];
  
let output = input.reduce((a,v) => {
   let {secId,...item} = v
   let obj = a.find(i => i.secId === secId)
   if(obj){
     obj.stuDetails.push(item)
   }else{
     a.push({'secId':secId,'stuDetails':[item]})
   }
   return a
},[])
console.log(output)

  • Related