JavaScript – Convert 2D Array to Object

In JavaScript, you can convert a 2D array into an object using various approaches. One common approach is to use the reduce() method or a simple loop to iterate through the 2D array and construct an object.

Methods to Convert 2D Array to Object

  • Using reduce()
  • Using a Simple Loop
  • Using Object.fromEntries()

Using reduce()

const arr = [
  ["name", "John"],
  ["age", 30],
  ["city", "New York"]
];

const obj = arr.reduce((acc, [key, value]) => {
  acc[key] = value;
  return acc;
}, {});

console.log(obj);

Output of the above will be

{ name: 'John', age: 30, city: 'New York' }

In this example, we used reduce() method. The initial value of the accumulator (acc) is an empty object {}. The reduce() the function iterates through each element of the 2D array.

For each sub-array, it destructures the key and value and assigns the value to the key in the accumulator object.

Using a Simple Loop

const arr = [
  ["name", "John"],
  ["age", 30],
  ["city", "New York"]
];

const obj = {};
for (const [key, value] of arr) {
  obj[key] = value;
}

console.log(obj);

Output of the above will be

{ name: 'John', age: 30, city: 'New York' }

This method uses a for…of loop to iterate through the 2D array.

During each iteration, the loop destructures the current sub-array into key and value. It then assigns the value to the key in an initially empty object (obj)

Using Object.fromEntries()

const arr = [
  ["name", "John"],
  ["age", 30],
  ["city", "New York"]
];

const obj = Object.fromEntries(arr);
console.log(obj); 

Output of the above will be

{ name: 'John', age: 30, city: 'New York' }

The Object.fromEntries() method transforms a list of key-value pairs (as arrays) into an object.

In this method, the 2D array is directly passed to Object.fromEntries(). It creates an object from the sub-arrays, where the first element of each sub-array becomes the key and the second element becomes the value.

Similar Reads