EN
JavaScript - create object from 2d array
1 answers
0 points
How can I convert 2D array to an object?
Let's say I have the following array of key/value pairs:
xxxxxxxxxx
1
[ [ 'a', 1 ], [ 'b', 2 ], [ 'c', 3 ] ]
and the result I want to get is:
xxxxxxxxxx
1
var object = {
2
a: 1,
3
b: 2,
4
c: 3
5
};
1 answer
0 points
1. Using reduce()
method (ES6+)
You can use reduce()
method to initialize the accumulator with an empty object which will be returned as a result. Then, on every iteration, assign the current
value as the key
of the accumulator and set its value. At the end it returns the accumulator
object.
xxxxxxxxxx
1
const arrayToObject = (array) => {
2
return array.reduce((accumulator, current) => {
3
const key = current[0];
4
const value = current[1];
5
accumulator[key] = value;
6
return accumulator;
7
}, {});
8
};
9
10
11
// Usage example
12
13
const myArray = [
14
['a', 1],
15
['b', 2],
16
['c', 3],
17
];
18
19
const myObject = arrayToObject(myArray);
20
21
console.log(JSON.stringify(myObject)); // { c: 1, a: 2, b: 3 }
2. Alternative solution
As an alternative solution for older versions of JavaScript, you can simply loop through the array, for example using forEach()
, to assign the key/value pairs to an empty object and return it at the end.
xxxxxxxxxx
1
function arrayToObject(array) {
2
var object = {};
3
array.forEach((val) => {
4
var key = val[0];
5
var value = val[1];
6
object[key] = value; // adds key and value to the object
7
});
8
return object;
9
}
10
11
12
// Usage example
13
14
var myArray = [
15
['a', 1],
16
['b', 2],
17
['c', 3],
18
];
19
20
var myObject = arrayToObject(myArray);
21
22
console.log(JSON.stringify(myObject)); // { c: 1, a: 2, b: 3 }
References
0 commentsShow commentsAdd comment