Convert javascript array to object of same keys/values

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

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 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.

var source = [ "australia", "brazil", "USA", "Japan"];

var obj = source.reduce(function(o, val) { o[val] = val; return o; }, {});



  australia: 'australia',
  brazil: 'brazil',
  USA: 'USA',
  Japan: 'Japan'

To know other ways to convert array to object read, How to convert an array to object in javascript?

Related Topics:

How To Remove Object From Array In JavaScript?

How To Convert An Array To Object In Javascript?

How To Convert An Array To String In Javascript

Convert array to string with brackets and quotes in JavaScript

💾 Recommended Articles