JavaScript - Convert an array to key value pair

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.

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 }


raja
Published on 30-Sep-2020 16:51:57
Advertisements