Converting array of objects to an object in JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

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.

We will use the Array.prototype.reduce() method to construct an object from the array.

Therefore, let’s write the code for this function −

Example

The code for this will be −

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

The output in the console will be −

{ Rahul: 89, Vivek: 88, Rakesh: 75, Sourav: 82, Gautam: 91, Sunil: 79 }
raja
Published on 21-Oct-2020 15:46:18
Advertisements