Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a JSON string from a jagged array in javascript efficiently

I have a jagged array where the series of column names is contained in the first row of the array and the data is contained in subsequent rows. I need to convert this into a Json string containing a series of objects with property names extracted from the first row.

As an example if I have:

var arr = [["Age", "Class", "Group"], ["24", "C", "Prod"], ["25", "A", "Dev"], ["26", "B", "Test"]];

I need to end up with:

[
  {
    "Age": "24",
    "Class": "C",
    "Group": "Prod"
  },
  {
    "Age": "25",
    "Class": "A",
    "Group": "Dev"
  },
  {
    "Age": "26",
    "Class": "B",
    "Group": "Test"
  }
]

and I have written some code to do this:

var arr = [["Age", "Class", "Group"], ["24", "C", "Prod"], ["25", "A", "Dev"], ["26", "B", "Test"]];

var headings = arr[0]; /* Headings always contained in the first row*/
arr.shift(); /* Remove the first row of the array */

/* Create JSON string by iterating through each nested array and each of their respective values */
var jason = "[";
arr.forEach(function (x, y) {
  jason += "{";
  x.forEach(function (i, j) {
    jason += "\"" + headings[j] + "\":\"" + i + "\"";
    if (j < (x.length - 1)) {
      jason += ",";
    }
  })
  jason += "}";
  if (y < (x.length - 1)) {
    jason += ",";
  }
});
jason += "]";

console.log(jason);

I am trying to create a bigger dataset to test it on but I was hoping someone who knows a bit more about javascript than I do could help me determine if there is a more efficient way to do it.

For example, I have iterated through the jagged array using arr.forEach whereas I could have used a sequential for loop. Are there any performance concerns that I need to consider?

I should note that the length of each array in the jagged array is always the same. Thanks

like image 400
Palps Avatar asked Mar 06 '26 12:03

Palps


1 Answers

You can use a map alongside reduce.

We know that the first element of arr are the keys, so we can shift that out, then map each of the other elements and reduce them to objects:

const arr = [["Age", "Class", "Group"], ["24", "C", "Prod"], ["25", "A", "Dev"], ["26", "B", "Test"]];

const keys = arr.shift()

const out = arr.map(arr => arr.reduce((a, el, i) => (a[keys[i]] = el, a), {}))
console.log(out)
like image 178
Kobe Avatar answered Mar 08 '26 01:03

Kobe



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!