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
JavaScript - Convert an array to key value pair
Converting an array of objects to key-value pairs is a common task in JavaScript. This involves transforming structured data into a simple object where one property becomes the key and another becomes the value.
Problem Statement
Suppose we have an array of student objects like this:
const arr = [
{"name": "Rahul", "score": 89},
{"name": "Vivek", "score": 88},
{"name": "Rakesh", "score": 75},
{"name": "Sourav", "score": 82},
{"name": "Gautam", "score": 91},
{"name": "Sunil", "score": 79}
];
We need to convert this array into an object where the name becomes the key and score becomes the value.
Method 1: Using for Loop
const arr = [
{"name": "Rahul", "score": 89},
{"name": "Vivek", "score": 88},
{"name": "Rakesh", "score": 75},
{"name": "Sourav", "score": 82},
{"name": "Gautam", "score": 91},
{"name": "Sunil", "score": 79}
];
const buildObject = arr => {
const obj = {};
for(let i = 0; i
{ Rahul: 89, Vivek: 88, Rakesh: 75, Sourav: 82, Gautam: 91, Sunil: 79 }
Method 2: Using Array.reduce() (Recommended)
The reduce() method provides a more functional approach:
const arr = [
{"name": "Rahul", "score": 89},
{"name": "Vivek", "score": 88},
{"name": "Rakesh", "score": 75},
{"name": "Sourav", "score": 82},
{"name": "Gautam", "score": 91},
{"name": "Sunil", "score": 79}
];
const buildObjectWithReduce = arr => {
return arr.reduce((acc, current) => {
acc[current.name] = current.score;
return acc;
}, {});
};
console.log(buildObjectWithReduce(arr));
{ Rahul: 89, Vivek: 88, Rakesh: 75, Sourav: 82, Gautam: 91, Sunil: 79 }
Method 3: Using Object.fromEntries() and map()
A more modern approach using ES2019 features:
const arr = [
{"name": "Rahul", "score": 89},
{"name": "Vivek", "score": 88},
{"name": "Rakesh", "score": 75}
];
const buildObjectFromEntries = arr => {
return Object.fromEntries(
arr.map(item => [item.name, item.score])
);
};
console.log(buildObjectFromEntries(arr));
{ Rahul: 89, Vivek: 88, Rakesh: 75 }
Comparison
| Method | Readability | Performance | Browser Support |
|---|---|---|---|
| for Loop | Good | Fastest | All browsers |
| Array.reduce() | Excellent | Good | ES5+ |
| Object.fromEntries() | Very Good | Good | ES2019+ |
Common Use Cases
This pattern is useful for:
- Creating lookup tables from API data
- Converting arrays to dictionaries for faster access
- Transforming data for state management in frameworks
Conclusion
Use Array.reduce() for most cases as it's functional, readable, and well-supported. For modern environments, Object.fromEntries() with map() offers the cleanest syntax.
Advertisements
