Convert Array to Object with same keys/values – JavaScript

In this article we will learn how we can convert javascript array to object of same keys/values in JavaScript.

The reduce() method in JavaScript allows transforming arrays into different values by iterating through the array elements. One common use case for reduce() is converting an array into an object where the array values become the object properties with the same keys and values.

So, suppose we have an array, [ "australia", "brazil", "USA", "Japan" ] and now we have to convert it to an Object with same key and value, example { australia : "australia", brazil : "brazil", USA : "USA", japan : "japan" }.

So to convert it into the same keys/value pair object we will be using the reduce() method of javascript.

The reduce() method executes a reducer function for each value in an array and return a single value which is the accumulated result.

Convert Array to Object with same key/value pair in JavaScript.

The reduce() method takes a callback function that gets called on each element in the array. This callback accepts four arguments:

  • Accumulator – The accumulated value returned each iteration
  • Current Value – The current element
  • Current Index – The index of the current element
  • Source Array – The array reduce was called on

To convert the array to an object with matching keys and values, we can build up the object in the accumulator on each iteration:

let arr = ['Australia', 'Brazil', 'USA', 'Japan'];

let obj = arr.reduce((acc, curr) => {
  acc[curr] = curr;
  return acc; 
}, {});

OUTPUT :

{
  Australia: 'Australia',
  Brazil: 'Brazil',
  USA: 'USA',
  Japan: 'Japan'
}

We start with an empty object {} as the initial value for the accumulator. On each iteration, the current array element is added as a key and value.

This gives us the desired object with the same key/value pairs as the original array.

Conclusion:

The reduce() method in JavaScript provides a concise way to transform an array into an object with matching keys and values.

By accumulating the object and adding each array element as a property, reduce() can map the array data into the equivalent object representation. This is a useful way of converting array data into objects.


Related Topics:

Convert array to string with brackets and quotes in JavaScript

Scroll to Top