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 convert a 2D Javascript array to object with identifiers

What’s the best way to convert a 2D array into an object with identifiers that count up?

There could be an unlimited number of identifiers in the object – based on what’s in the array.

So in the array we might have

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

data: [
    ["Lisa", "Heinz"],
    ["Bob", "Sleigh"]
  ]

And we’d be keen that the array looked something like this in the end:

data: {
    person1 {
{name: Lisa}, 
{last_name: Heinz}
},
person2 {
{name: Bob},
{last_name: Sleigh}
}
}
    

Using map I can create an array of objects, but this isn’t quite

json = formData.map(function(x) {
    return {    
        "name": x[0],
        "last_name": x[1]
    }
})
console.log(json);

>Solution :

Something like this? I changed your object structure a bit to be easier to access.

let newDataObj = {}
for (let person of data) {
    const identifier = `person${data.indexOf(person)}`;
    const [name, last_name] = person;
    newDataObj[identifier] = { name, last_name };
}
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