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

JS: transform header and body array to single json

I want to transform 2 arrays into 1 final json object.
The first array contains the header data and the second one the body.
Each row of the body should be assigned to a column of the header.
This image illustrates the input and the expected output:

enter image description here

I’m using 3 nested loops to assign the data.
The keys are working but I’m stucked getting the correct data because somehow only data from the last body row are extracted.

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

There must be a minor thing, I’m missing in my code:

const header = ['A','B','C','D']
const body = [
  ["A1","A2","A3","A4","A5","A6"],
  ["B1","B2","B3","B4","B5","B6"],
  ["C1","C2","C3","C4","C5","C6"],
  ["D1","D2","D3","D4","D5","D6"],
];

const json = [];

for (let y = 0; y < body[0].length; y++)
{
  const line = {};
  for(const hl of header)
  {
    for(const bo of body)
    {
      line[hl] = bo[y];
    }
  } 
  json.push(line);
}

console.log(json);

>Solution :

I’d say your gut feeling is correct, but you’re always replacing the column values with the values of the last column.

Plus, at least as I understand your drawing, you want an array of objects, where the key is the header and the value is the corresponding value, i.e. I understand you want [{A:'A1', B: 'B1', C: 'C1', D: 'D1'}, …] and not [['A1', 'B1', 'C1', 'D1'], …]. Correct?

Below is an approach using [].map() and [].reduce(), which, to me (who is used to this style of writing, I admit), makes it a lot clearer what happens:

const header = ['A','B','C','D']
const body = [
  ["A1","A2","A3","A4","A5","A6"],
  ["B1","B2","B3","B4","B5","B6"],
  ["C1","C2","C3","C4","C5","C6"],
  ["D1","D2","D3","D4","D5","D6"],
];

console.log(body[0].map((_, row) =>
  header.reduce((json, key, col) => ({
    ...json,
    [key]: body[col][row]
  }), {})));
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