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
Creating a JavaScript Object from Single Array and Defining the Key Value?
JavaScript provides several ways to create objects from arrays and define key-value pairs. This is useful when transforming data structures or converting between different formats.
Using Object.entries() with map()
The most common approach uses Object.entries() to convert an object into an array of key-value pairs, then map() to transform the structure:
var studentObject = {
101: "John",
102: "David",
103: "Bob"
};
var studentDetails = Object.entries(studentObject).map(([studentId, studentName]) => ({
studentId,
studentName
}));
console.log(studentDetails);
[
{ studentId: '101', studentName: 'John' },
{ studentId: '102', studentName: 'David' },
{ studentId: '103', studentName: 'Bob' }
]
Creating Object from Single Array
You can also create objects from a single array by defining how keys and values are assigned:
// From array of strings to indexed object
const fruits = ["apple", "banana", "cherry"];
const fruitObject = fruits.reduce((obj, fruit, index) => {
obj[index] = fruit;
return obj;
}, {});
console.log(fruitObject);
{ '0': 'apple', '1': 'banana', '2': 'cherry' }
Using Array Elements as Keys
Transform array elements into object keys with default values:
const colors = ["red", "green", "blue"];
const colorObject = colors.reduce((obj, color) => {
obj[color] = true; // or any default value
return obj;
}, {});
console.log(colorObject);
{ red: true, green: true, blue: true }
Comparison of Methods
| Method | Use Case | Output |
|---|---|---|
Object.entries() + map() |
Object to array of objects | Array of key-value objects |
reduce() with index |
Array to indexed object | Object with numeric keys |
reduce() with elements |
Array elements as keys | Object with string keys |
Conclusion
Use Object.entries() with map() to transform existing objects, and reduce() to create new objects from arrays. Choose the method based on your desired output structure.
Advertisements
