JavaScript How to Convert Array to Object Easily
Object.fromEntries(array) if the array contains key-value pairs, or by using array.reduce((obj, item) => { obj[key] = value; return obj; }, {}) to build an object manually.Examples
How to Think About It
Algorithm
Code
const arr = [['a', 1], ['b', 2]]; const obj = Object.fromEntries(arr); console.log(obj); // For array of objects const arr2 = [{id: 'x', value: 10}, {id: 'y', value: 20}]; const obj2 = arr2.reduce((acc, item) => { acc[item.id] = item.value; return acc; }, {}); console.log(obj2);
Dry Run
Let's trace converting [['a', 1], ['b', 2]] to an object using Object.fromEntries.
Start with array
[['a', 1], ['b', 2]]
Convert using Object.fromEntries
Object.fromEntries([['a', 1], ['b', 2]])
Resulting object
{"a":1,"b":2}
| Key | Value |
|---|---|
| a | 1 |
| b | 2 |
Why This Works
Step 1: Using Object.fromEntries
This method takes an array of [key, value] pairs and creates an object where each key maps to its value.
Step 2: Using reduce for custom arrays
When the array has objects, reduce lets you build an object by assigning keys and values from each element.
Step 3: Returning the object
After processing all elements, the final object contains all keys and values from the array.
Alternative Approaches
const arr = [{id: 'x', value: 10}, {id: 'y', value: 20}]; const obj = {}; arr.forEach(item => { obj[item.id] = item.value; }); console.log(obj);
const arr = [{id: 'x', value: 10}, {id: 'y', value: 20}]; const obj = Object.fromEntries(arr.map(item => [item.id, item.value])); console.log(obj);
Complexity: O(n) time, O(n) space
Time Complexity
The conversion loops through each element once, so time grows linearly with array size.
Space Complexity
A new object is created with one property per array element, so space grows linearly.
Which Approach is Fastest?
Using Object.fromEntries is fastest for arrays of pairs; reduce and forEach have similar performance for arrays of objects.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Object.fromEntries | O(n) | O(n) | Arrays of [key, value] pairs |
| reduce | O(n) | O(n) | Arrays of objects with keys and values |
| forEach loop | O(n) | O(n) | Simple, readable conversion for arrays of objects |