In this article, we will learn how to convert a two-dimensional array to an object. A two-dimensional array can have any number of rows and two columns.
Example:
Input: [
["John", 12],
["Jack", 13],
["Matt", 14],
["Maxx", 15]
]
Output: {
"John": 12,
"Jack": 13,
"Matt": 14,
"Maxx": 15
}
The below approaches can be followed to solve the problem.
Approach 1: In this approach, we create an empty object and use the Array.forEach() method to iterate over the array. On every iteration, we insert the first item of the child array into the object as a key and the second item as a value. Then it returns the object after the iterations.
Example: In this example, we will be using the forEach() method to convert the two-dimensional array into an object.
Javascript
function arr2obj(arr) {
let obj = {};
arr.forEach((v) => {
let key = v[0];
let value = v[1];
obj[key] = value;
});
return obj;
}
console.log(
arr2obj([
[ "John" , 12],
[ "Jack" , 13],
[ "Matt" , 14],
[ "Maxx" , 15],
])
);
|
Output{ John: 12, Jack: 13, Matt: 14, Maxx: 15 }
Approach 2: In this approach, we will use the Array.reduce() method and initialize the accumulator with an empty object. On every iteration, we assign the current value as the key’s value of the accumulator and return the accumulator. Then it returns the object after the iterations.
Example: In this example, we will be using the reduce() method to convert the two-dimensional array into an object.
Javascript
function arr2obj(arr) {
return arr.reduce(
(acc, curr) => {
let key = curr[0];
let value = curr[1];
acc[key] = value;
return acc;
},
{}
);
}
console.log(
arr2obj([
[ "Eren" , "Yeager" ],
[ "Mikasa" , "Ackermann" ],
[ "Armin" , "Arlelt" ],
[ "Levi" , "Ackermann" ],
])
);
|
Output{
Eren: 'Yeager',
Mikasa: 'Ackermann',
Armin: 'Arlelt',
Levi: 'Ackermann'
}
Approach 3: In this approach, we first flatten the array using the Array.flat() method so that we get a one-dimensional array. We can then create an empty object and iterate the array to assign evenly positioned values as the key of the object and oddly positioned values as the value.
Example: In this example, we will be using the flat() method to convert the two-dimensional array into an object.
Javascript
function arr2obj(arr) {
arr = arr.flat();
let obj = {};
for (let i = 0; i < arr.length; i++) {
if (i % 2 == 0) {
let key = arr[i];
let value = arr[i + 1];
obj[key] = value;
}
}
return obj;
}
console.log(
arr2obj([
[ "Max" , 19],
[ "Chloe" , 20],
[ "Nathan" , 22],
[ "Mark" , 31],
])
);
|
Output{ Max: 19, Chloe: 20, Nathan: 22, Mark: 31 }