Convert javascript array to object of same keys/values
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
Use Array forEach() to loop through JavaScript object
FInd out how to use forEach in an object and return key, value and also convert it's properties to an array using JavaScript.
JavaScript hasOwnProperty() method of an Object
Tutorial about the Javascript hasOwnProperty() method of an object, its use, advantages and limitations.
How to add getter to an existing JavaScript Object
Short tutorial on adding a getter to an existing JavaScript object using Object.defineProperty method.
How to add dynamic Key to an object in JavaScript
Short tutorial on how to create and add dynamic key to an object in JavaScript using bracket syntax and ES6 methods.
