- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
JavaScript - Convert an array to key value pair
Suppose we have an array 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 are required to write a JavaScript function that takes in one such array and constructs an object where name value is the key and the score value is their value.
Use the Array.prototype.reduce() method to construct an object from the array.
Example
Following is the code −
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 < arr.length; i++){ const { name, score } = arr[i]; obj[name] = score; }; return obj; }; console.log(buildObject(arr));
Output
This will produce the following output in console −
{ Rahul: 89, Vivek: 88, Rakesh: 75, Sourav: 82, Gautam: 91, Sunil: 79 }
Advertisements