Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
How to convert array to object in JavaScript
Converting arrays to objects is a common task in JavaScript. There are several approaches depending on your data structure and requirements.
Method 1: Array of Arrays to Objects with Alphabetic Keys
Let's convert a nested array structure into objects with keys as English alphabet letters:
const data = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]];
const dataArr = data.map(arr => {
return arr.reduce((acc, cur, index) => ({
...acc,
[String.fromCharCode(97 + index)]: cur
}), Object.create({}))
});
console.log(dataArr);
[
{ a: 1, b: 2, c: 3, d: 4 },
{ a: 5, b: 6, c: 7, d: 8 },
{ a: 9, b: 10, c: 11, d: 12 }
]
Method 2: Simple Array to Object with Index Keys
Convert a simple array to an object using array indices as keys:
const fruits = ['apple', 'banana', 'orange'];
const fruitsObj = Object.assign({}, fruits);
console.log(fruitsObj);
// Alternative using spread operator
const fruitsObj2 = {...fruits};
console.log(fruitsObj2);
{ '0': 'apple', '1': 'banana', '2': 'orange' }
{ '0': 'apple', '1': 'banana', '2': 'orange' }
Method 3: Array to Object with Custom Keys
Create objects from arrays using custom key-value mapping:
const names = ['John', 'Jane', 'Bob'];
const ages = [25, 30, 35];
const people = names.reduce((acc, name, index) => {
acc[name] = ages[index];
return acc;
}, {});
console.log(people);
{ John: 25, Jane: 30, Bob: 35 }
Method 4: Using Object.fromEntries()
Convert an array of key-value pairs into an object:
const entries = [['name', 'John'], ['age', 30], ['city', 'New York']];
const person = Object.fromEntries(entries);
console.log(person);
// From array with map
const colors = ['red', 'green', 'blue'];
const colorObj = Object.fromEntries(
colors.map((color, index) => [color, index])
);
console.log(colorObj);
{ name: 'John', age: 30, city: 'New York' }
{ red: 0, green: 1, blue: 2 }
Comparison
| Method | Use Case | Performance | Browser Support |
|---|---|---|---|
| reduce() | Complex transformations | Good | ES5+ |
| Object.assign() | Index-based keys | Fast | ES6+ |
| Spread operator | Index-based keys | Fast | ES6+ |
| Object.fromEntries() | Key-value pairs | Fast | ES2019+ |
Conclusion
Choose the method based on your data structure: use reduce() for complex transformations, Object.assign() for simple conversions, and Object.fromEntries() for key-value pair arrays. Each method serves different conversion needs efficiently.
Advertisements
