0

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);
2
  • Does this answer your question? 2-dimensional array to object (JavaScript) Commented Oct 31, 2022 at 19:22
  • Not quite. The code example I currently have is based off this @pilchard - but it returns an array of objects - as I currently have. Commented Oct 31, 2022 at 19:26

1 Answer 1

1

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 };
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.