I have a 2-dimensional array that looks like this:
var myArray = [
['Name', 'Age', 'Profession'],
['John', 34, 'Teacher'],
['Jane', 45, 'Artist']
];
I want to transform this array to an object that looks like this:
var myObject =
{
"Name":
{
"Name": "Name",
"Age": "Age",
"Profession": "Profession"
}
"John":
{
"Name": "John",
"Age": 34,
"Profession": "Teacher"
}
"Jane":
{
"Name": "Jane",
"Age": 45,
"Profession": "Artist"
}
};
In another thread I came across Array.prototype.reduce() and I was able to do the following:
var myObject = myArray.reduce(function(result, currentItem) {
result[currentItem[0]] = currentItem;
return result;
}, {})
Logger.log(myObject);
// {John=[John, 34.0, Teacher], Jane=[Jane, 45.0, Artist], Name=[Name, Age, Profession]}
However, I don't know how to apply reduce() to get a nested object or if I need a different approach here.
Andreas
Edit:
- I am looking for an dynamical solution, that is: I don't know beforehand how many elements my array contains or what their values are.
- I'd prefer a solution that is faster and more elegant than iterating through all elements (if possible).