What is Array Object ?
JavaScript, arrays are a special type of object used for storing and manipulating lists of values. Despite their name, arrays in JavaScript are more flexible than traditional arrays in other languages, as they can hold a mixture of data types and can dynamically resize. You can think of an array in JavaScript as an object with a special structure optimized for handling sequential data.
There are two main ways to convert an array to an object in JavaScript:
- Using the
Object.assign()
method: TheObject.assign()
method takes one or more source objects and copies their properties to a target object. To convert an array to an object using theObject.assign()
method, we can pass the array as the source object and an empty object as the target object.
const arr = [1, 2, 3];
const obj = Object.assign({}, arr);
console.log(obj); // {0: 1, 1: 2, 2: 3}
Using the Object.fromEntries()
method: The Object.fromEntries()
method takes an iterable of key-value pairs and returns an object with those properties. To convert an array to an object using the Object.fromEntries()
method, we can use the Array.prototype.map()
method to create an iterable of key-value pairs from the array.
const arr = [["name", "John Doe"], ["age", 30]];
const obj = Object.fromEntries(arr.map(([key, value]) => [key, value]));
console.log(obj); // {name: "John Doe", age: 30}