Home > database >  How to convert a 2D Javascript array to object with identifiers
How to convert a 2D Javascript array to object with identifiers

Time:11-01

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

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);

CodePudding user response:

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 };
}
  • Related