Reputation: 475
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:
Upvotes: 2
Views: 83
Reputation: 1718
myArray.reduce(
function ( r, a )
{
var row = a.reduce(
function ( rr, cc, i )
{
rr[ myArray[ 0 ][ i ] ] = cc;
return rr;
}, {} );
r[ a[ 0 ] ] = row;
return r;
}, {} );
The idea is that do the same reduce at each row.
var myArray = [
['Name', 'Age', 'Profession'],
['John', 34, 'Teacher'],
['Jane', 45, 'Artist']
];
var result = myArray.reduce(
function(r, a) {
var row = a.reduce(
function(rr, cc, i) {
rr[myArray[0][i]] = cc;
return rr;
}, {});
r[a[0]] = row;
return r;
}, {});
document.write('<pre>' + JSON.stringify(result, 0, 4) + '</pre>');
Upvotes: 1
Reputation: 386883
A solution with reduce and an object and some nested properties.
var myArray = [['Name', 'Age', 'Profession'], ['John', 34, 'Teacher'], ['Jane', 45, 'Artist']],
result = myArray.reduce(function (r, a) {
// get the first element ('Name', 'John', 'Jane') of myArray and take it as a key
// for the object. generate a new object if there is no object available
// read here: r.Name = r.Name || {}
r[a[0]] = r[a[0]] || {};
// iterate over ['Name', 'Age', 'Profession']
myArray[0].forEach(function (b, i) {
// assign the according value to the according property of the object
// read here: r.Name.Name = 'Name'
// next r.Name.Age = 'Age'
r[a[0]][b] = a[i];
});
return r;
}, {});
document.write('<pre>' + JSON.stringify(result, 0, 4) + '</pre>');
Upvotes: 2
Reputation: 3062
I think that the easiest way to do this could be using map
function
var myArray = [
['Name', 'Age', 'Profession'],
['John', 34, 'Teacher'],
['Jane', 45, 'Artist']
];
var myObjects = myArray.map(function(el) {
return {
'Name': el[0],
'Age': el[1],
'Profession': el[2]
}
});
The other way is to just use on for statement
for(int i=1;myArray.length;i++)
{
var el = myArray[i];
myObjects2[el[0]] = {
'Name': el[0],
'Age': el[1],
'Profession': el[2]
}
}
Upvotes: 0