Convert javascript array to object of same keys/values

javascript1 min read

This article is about how to convert javascript array to object of same keys/values. To convert the array to object of same keys/values pair we will use reduce() method in javascript.

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' }

Related Topics:

Convert array to string with brackets and quotes in JavaScript

Related Posts