I want to convert the following array:
const data = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]];
to the following object:
const data = [
{
a: 1,
b: 2,
c: 3,
d: 4
},
{
a: 5,
b: 6,
c: 7,
d: 8
},
{
a: 9,
b: 10,
c: 11,
d: 12
}
];
How do I do it using loop or some other way, of course?
2 Answers 2
This is a basic map / reduce operation where you map the outer array to a new one where each value (array) is reduced to a single object.
Given the simple nature of each value (a single array with four values), you can skip Array.prototype.reduce() for some array destructuring.
For example
const data = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]];
const newData = data.map(([ a, b, c, d ]) => ({ a, b, c, d }))
console.info(newData)
Note that this really hinges on knowing the data structure and no surprises (more or fewer elements in each array for example).
If you wanted a much more robust version, you'll want something like this
const data = [[1, 2, 3, 4], [5, 6, 7], [8, 9, 10, 11, 12]];
const newData = data.map(arr => arr.reduce((obj, val, idx) => ({
...obj,
[String.fromCharCode(97 + idx)]: val
}), Object.create(null)))
console.info(newData)
The only thing to worry about here is if your arrays contain more than 26 elements. Then your object keys are going to get weird.
Comments
You can use Array.prototype.map() combined with Array.prototype.reduce()
Code:
const alphabet = [...'abcdefghijklmnopqrstuvwxyz'];
const data = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]];
const reasult = data.map(arr => arr.reduce((a, c, i) => (a[alphabet[i]] = c, a), {}));
console.log(reasult);
Array.prototype.mapandArray.prototype.reduce