Home > Back-end >  Facing issue with Javascript array
Facing issue with Javascript array

Time:12-15

I am getting an array of object data from service as below: outputs

 array=   [
    {id:1,Name:GHI,Gender:Male,DOB:12/1/2020},
    {id:1,Name:GHI,Gender:Female,DOB:10/1/2020},
    {id:2,Name:ABC,Gender:Male,DOB:02/02/2020},
    {id:2,Name:ABC,Gender:Female,DOB:03/04/2019},
    {id:3,Name:EFG,Gender:Male,DOB:09/09/2010},
    {id:3,Name:EFG,Gender:Female,DOB:08/07/2021}
    ]

I have applied group By function and mapping by using the Key

  let key="id";

    const groupBy=(array,key)=>{
    return Object.entries(array.reduce((result,currentvalue)=>{
    (result[currentValues[key]]=result[currentValue[key]]||[]).push(
    currentvalue
    );
    return result;
    },{})).map(v=>({[key]:v[0],data:v[1]})));
    };

I am able to get data like this

[
{
Id:1,
data:
   [
    {id:1,Name:GHI,Gender:Male,DOB:12/1/2020},
    {id:1,Name:GHI,Gender:Female,DOB:10/1/2020}
  ]
},
{
Id:2,
data:
   [
   {id:2,Name:ABC,Gender:Male,DOB:02/02/2020},
   {id:2,Name:ABC,Gender:Female,DOB:03/04/3019}
   ]
}...
]

But I need the out put some thing like this I need to group by Id but need the Name of Id something like this

[
 {
  Name:GHI,
  data:[
    {id:1,Name:GHI,Gender:Male,DOB:12/1/2020},
    {id:1,Name:GHI,Gender:Female,DOB:10/01/2020}
   ]
 },
 {
  Name:ABC,
  data:[
      {id:2,Name:ABC,Gender:Male,DOB:02/02/2020},
      {id:2,Name:ABC,Gender:Female,DOB:03/04/2019}
    ]
 },
 {
  Name:EFG,
  data:[
     {id:3,Name:EFG,Gender:Male,DOB:09/09/2010},
     {id:3,Name:EFG,Gender:Male,DOB:08/07/2021}
     ]
 }
]

Please let me know how to retireve data in expected format to display on UI.

CodePudding user response:

try with the below code.

    var arr =   [
    {id:1,Name:"GHI",Gender:"Male",DOB:"12/1/2020"},
    {id:1,Name:"GHI",Gender:"Female",DOB:"10/1/2020"},
    {id:2,Name:"ABC",Gender:"Male",DOB:"02/02/2020"},
    {id:2,Name:"ABC",Gender:"Female",DOB:"03/04/2019"},
    {id:3,Name:"EFG",Gender:"Male",DOB:"09/09/2010"},
    {id:3,Name:"EFG",Gender:"Female",DOB:"08/07/2021"}
    ]

let temp = {}
arr.forEach((obj) => {
    temp[obj.Name] = temp[obj.Name] || [];
    temp[obj.Name].push(obj);
});

let output = Object.entries(temp).map(obj => {
   return {"Name": obj[0], "data": obj[1]}
});

console.log(JSON.stringify(output, null, 2));

CodePudding user response:

You may go simpler and more readable:

let result = {};
for (const data of array) {
  const { Name } = data; 
  if (!result[Name]) {
    result[Name] = { Name, data: [data] };
  } else {
    result[Name].data.push(data);
  }
}
  • Related