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 split an array of objects with a single row into multiple rows in javascript

I have the following array with one object:

[{
  "0key1": "a33",
  "0key2": "Aab",
  "0key3": "i",
  "1key1": "e78",
  "1key2": "Vib",
  "1key3": "j",
  "2key1": "c99",
  "2key2": "Aig",
  "2key3": "k"
}]

I would like to split it into three "key": "value" per row as shown below:

[
  {"0key1":"a33","0key2":"Aab","0key3":"i"},
  {"1key1":"e78","1key2":"Vib","1key3":"j"},
  {"2key1":"c99","2key2":"Aig","2key3":"k"}
]

Please help me achieve that.

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

>Solution :

I would use reduce and a nullish coalescing assigment

const input = [{ 
  "0key1": "a33", "0key2": "Aab", "0key3": "i",
  "1key1": "e78", "1key2": "Vib", "1key3": "j",
  "2key1": "c99",  "2key2": "Aig", "2key3": "k"
}]
const output = Object.entries(input[0]).reduce((acc,cur) => {
  const key = cur[0];
  const [mainIdx,idx] = key.split("key");
  acc[mainIdx] ??= {}; // nullish coalescing assignment
  acc[mainIdx][key]=cur[1];
  return acc;
}
,[])
console.log(output)
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