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; }, {});

console.log(obj);

OUTPUT :

{
  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?


💾 Recommended Articles