Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to add data in the below format?

I am stuck to add data in JS. I am not sure whether this could be done or not. I have tried but I failed to do so.

The below data needs to send to prepare in the API format.

0: { id2: 79, id3: 18}
1: { id2: 79, id3: 19}
2: { id2: 80, id3: 30}

I have to send the data to api in the below format.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

For example: in APi format demands: id2 becomes key and id3 is value will be added to the same key and if there is new id2 then new key becomes and value will be added

"data1":{
"79":[18,19],
"80": [30],
}

>Solution :

let data = [  { id2: 79, id3: 18},  { id2: 79, id3: 19},  { id2: 80, id3: 30}];

let data1 = data.reduce((acc, current) => {
  if (!acc[current.id2]) {
    acc[current.id2] = []
  }
  acc[current.id2].push(current.id3)
  return acc
}, {})

console.log(data1)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading