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 dictionary into list of JavaScript objects?
In JavaScript, you can convert a dictionary (object) into a list of objects using various methods. The most common approaches are Object.values(), Object.entries(), and Object.keys() with mapping.
What is a Dictionary in JavaScript?
A dictionary in JavaScript is typically an object with key-value pairs where values can be primitives, arrays, or other objects.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Dictionary to List Conversion</title>
</head>
<body>
<h1>Convert Dictionary to List of Objects</h1>
<button onclick="convertDictionary()">Convert Dictionary</button>
<div id="output"></div>
<script>
const dictionary = {
A: { id: 1, name: "Apple", type: "Fruit" },
B: { id: 2, name: "Ball", type: "Toy" },
C: { id: 3, name: "Cat", type: "Animal" },
D: { id: 4, name: "Dog", type: "Animal" }
};
function convertDictionary() {
// Method 1: Using Object.values()
const listFromValues = Object.values(dictionary);
console.log("Using Object.values():", listFromValues);
// Method 2: Using Object.entries() with map
const listFromEntries = Object.entries(dictionary).map(([key, value]) => ({
key: key,
...value
}));
console.log("Using Object.entries():", listFromEntries);
// Display results
document.getElementById('output').innerHTML =
'<h3>Results (check console for details):</h3>' +
'<p>Object.values() length: ' + listFromValues.length + '</p>' +
'<p>Object.entries() length: ' + listFromEntries.length + '</p>';
}
</script>
</body>
</html>
Method 1: Using Object.values()
This method extracts all values from the dictionary and returns them as an array.
const dictionary = {
user1: { name: "John", age: 25 },
user2: { name: "Jane", age: 30 },
user3: { name: "Bob", age: 35 }
};
const userList = Object.values(dictionary);
console.log("List of users:", userList);
console.log("Total users:", userList.length);
List of users: [
{ name: 'John', age: 25 },
{ name: 'Jane', age: 30 },
{ name: 'Bob', age: 35 }
]
Total users: 3
Method 2: Using Object.entries() with Keys
This method preserves both keys and values, creating objects that include the original key.
const products = {
P001: { name: "Laptop", price: 999 },
P002: { name: "Mouse", price: 25 },
P003: { name: "Keyboard", price: 75 }
};
const productList = Object.entries(products).map(([id, details]) => ({
id: id,
...details
}));
console.log("Product list with IDs:");
productList.forEach(product => {
console.log(`${product.id}: ${product.name} - $${product.price}`);
});
Product list with IDs: P001: Laptop - $999 P002: Mouse - $25 P003: Keyboard - $75
Method 3: Using Object.keys() with Mapping
const scores = {
math: 85,
english: 92,
science: 78,
history: 88
};
const subjectList = Object.keys(scores).map(subject => ({
subject: subject,
score: scores[subject],
grade: scores[subject] >= 90 ? 'A' : scores[subject] >= 80 ? 'B' : 'C'
}));
console.log("Subject scores:");
console.log(subjectList);
Subject scores:
[
{ subject: 'math', score: 85, grade: 'B' },
{ subject: 'english', score: 92, grade: 'A' },
{ subject: 'science', score: 78, grade: 'C' },
{ subject: 'history', score: 88, grade: 'B' }
]
Comparison of Methods
| Method | Preserves Keys | Use Case | Performance |
|---|---|---|---|
Object.values() |
No | When keys are not needed | Fastest |
Object.entries() |
Yes | When keys should be included | Medium |
Object.keys() + map |
Yes | Custom transformation needed | Slowest |
Real-World Example
// Converting user data from dictionary to array for API response
const userDatabase = {
"usr_001": { name: "Alice", email: "alice@example.com", role: "admin" },
"usr_002": { name: "Bob", email: "bob@example.com", role: "user" },
"usr_003": { name: "Charlie", email: "charlie@example.com", role: "user" }
};
// Convert for API response (include user IDs)
const apiResponse = Object.entries(userDatabase).map(([userId, userData]) => ({
userId,
...userData,
isActive: true
}));
console.log("API Response:");
console.log(JSON.stringify(apiResponse, null, 2));
API Response:
[
{
"userId": "usr_001",
"name": "Alice",
"email": "alice@example.com",
"role": "admin",
"isActive": true
},
{
"userId": "usr_002",
"name": "Bob",
"email": "bob@example.com",
"role": "user",
"isActive": true
},
{
"userId": "usr_003",
"name": "Charlie",
"email": "charlie@example.com",
"role": "user",
"isActive": true
}
]
Conclusion
Use Object.values() when you only need the values, and Object.entries() when you need to preserve the original keys. Choose the method based on whether you need the dictionary keys in your final array.
Advertisements
