0

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?

Penny Liu
18k5 gold badges89 silver badges109 bronze badges
asked Jun 13, 2019 at 3:00
1
  • 1
    Have you tried anything yet that you're having trouble with? I'd suggest you start by looking at Array.prototype.map and Array.prototype.reduce Commented Jun 13, 2019 at 3:01

2 Answers 2

7

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.

answered Jun 13, 2019 at 3:04
Sign up to request clarification or add additional context in comments.

Comments

1

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);

answered Jun 13, 2019 at 3:09

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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