Convert an Array to an Object in JavaScript
Last Updated :
08 Dec, 2023
The object is defined as a key-value pair while the array is the collection of homogeneous data. we need to convert an array into an object. both are used to store the data in different formats. we will see the approach for conversion of an array into an object.
These are the following ways to solve this problem:
The first approach is using the Object.assign() method. This method copies the values of all enumerable properties from source objects(one or more) to a target object.
Syntax:
Object.assign(target, ...sources);
Example: This example converts the array to an object by using Object.assign() method. To display it, JSON.stringify() method is used.
Javascript
let arr = [1, 2, 3, 4];
let obj = Object.assign({}, arr);
console.log(JSON.stringify(obj));
|
Output
{"0":1,"1":2,"2":3,"3":4}
In this method, we will traverse the array using a JavaScript for loop and assign each array element to the target object.
Example: In this example, the code converts the array to an object by creating a function that adds the array values one by one to the object. To display the object content, JSON.stringify() method is used.
Javascript
let arr = [ 'GFG1' , 'GFG2' , 'GFG3' , 'GFG4' ];
function toObject(arr) {
let rv = {};
for (let i = 0; i < arr.length; ++i)
rv[i] = arr[i];
return rv;
}
console.log(JSON.stringify(toObject(arr)));
|
Output
{"0":"GFG1","1":"GFG2","2":"GFG3","3":"GFG4"}
The Object.fromEntries() method in JavaScript is a standard built-in object which is used to transform a list of key-value pairs into an object. This method returns a new object whose properties are given by the entries of the iterable.
Syntax:
Object.fromEntries( iterable );
Example: In this example, we have used Object.from.entries() method to convert an Array to an Object in JavaScript
Javascript
let arr = [[ 'JS' , 'JavaScript' ], [ 'GFG' , 'GeeksforGeeks' ]];
let obj = Object.fromEntries(arr);
console.log(obj);
|
Output
{ JS: 'JavaScript', GFG: 'GeeksforGeeks' }
The Spread operator allows an iterable to expand in places where 0+ arguments are expected. It is mostly used in the variable array where there is more than 1 value is expected. It allows us the privilege to obtain a list of parameters from an array.
Syntax:
let variablename1 = [...value];
Example: In this example, we have used spread operator to convert array to object.
Javascript
const arr = [ "Geeks" , "for" , "Geeks" ];
const obj = {...arr};
console.log(obj);
|
Output
{ '0': 'Geeks', '1': 'for', '2': 'Geeks' }
Share your thoughts in the comments
Please Login to comment...