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

Convert 2D array to array of objects

I have been trying to convert this data:

var myArray = [
[1,2,3,4],
["1","2","3","4"],
["a", "b", "c", "d"]
]

to this:

var result = [
  {
    "num": 1,
    "str": "1",
    "let": "a"
  },
  {
    "num": 2,
    "str": "2",
    "let": "b"
  },
  {
    "num": 3,
    "str": "3",
    "let": "c"
  },
  {
    "num": 4,
    "str": "4",
    "let": "d"
  }
]

Any assistance will be extremely helpful. I have tried various iterations but none of them yield what I am hoping for.

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

I am trying to use this:

objectified_data = array_data.map(function(x) {
    return {    
        "num": x[0],
        "str": x[1],
        "let": x[2]
    }
})

But I cannot figure out how to make the homogenous set of array, heterogenous for this to work. Ultimately, I am trying to filter out certain keys, so the original data as it was is not working for that task

>Solution :

You can achieve this with a simple for

var myArray = [
  [1, 2, 3, 4],
  ["1", "2", "3", "4"],
  ["a", "b", "c", "d"]
]
const json = [];

for (let i = 0; i < myArray[0].length; i++) {
  json.push({
    num: myArray[0][i],
    let: myArray[1][i],
    str: myArray[2][i],
  });
}

console.log(json);
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