Reputation: 83
Using Array of array to object - javascript and Convert an array to an array of objects as a guide I tried to write a function that results in taking this array of array list:
var list = [['name', 'Sparky'], ['breed', 'lab'], ['age', 4]];
and converting it into this:
{
name : 'Sparky'
breed : 'lab',
age : 4
}
However, when I run the code below:
var list = [
['name', 'Sparky'],
['breed', 'lab'],
['age', 4]
];
function toObjects(data) {
var keys = data.shift(),
i = 0,
k = 0,
obj = null,
output = [];
for (i = 0; i < data.length; i++) {
obj = {};
for (k = 0; k < keys.length; k++) {
obj[keys[k]] = data[i][k];
}
output.push(obj);
}
return output;
}
var data = [
['name', 'Sparky'],
['breed', 'lab'],
['age', 4]
];
console.log(toObjects(data))
I get this:
console.log(toObjects(data)); //=>
[ { name: 'breed', Sparky: 'lab' },{ name: 'age', Sparky: 4 } ]
but I need the output to not have an extra array [ ] and to also be listed single file like this:
{
name : 'Sparky'
breed : 'lab',
age : 4
}
Any advice? Please and thank you!
Upvotes: 1
Views: 164
Reputation: 19212
I would use Array.prototype.reduce to perform your transformation as well as argument destructing. Take a look, the code is pretty simple :)
let list = [
['name', 'Sparky'],
['breed', 'lab'],
['age', 4]
];
function toObjects(data) {
// reduce iterates through every element in the `data` array
// and accumulates it into the object
let initialValue = {};
return data.reduce((obj, [key, value]) => {
obj[key] = value;
return obj;
}, initialValue); // this could be in-lined with `{}`
}
var data = [
['name', 'Sparky'],
['breed', 'lab'],
['age', 4]
];
console.log(toObjects(list))
Upvotes: 2
Reputation: 14604
You can use map function to achieve this
var list = [['name', 'Sparky'], ['breed', 'lab'], ['age', 4]];
var newObj = new Object();
list.forEach(function (arr) {
newObj[arr[0]] = arr[1];
});
console.log(newObj)
Upvotes: 0