Creating an array of objects based on another array of objects JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

Suppose, we have an array of objects containing data about likes of some users like this −

const arr = [
   {"user":"dan","liked":"yes","age":"22"},
   {"user":"sarah","liked":"no","age":"21"},
   {"user":"john","liked":"yes","age":"23"},
 ];

We are required to write a JavaScript function that takes in one such array. The function should construct another array based on this array like this −

const output = [
   {"dan":"yes"},
   {"sarah":"no"},
   {"john":"yes"},
];

Example

const arr = [
   {"user":"dan","liked":"yes","age":"22"},
   {"user":"sarah","liked":"no","age":"21"},
    {"user":"john","liked":"yes","age":"23"},
];
const mapToPair = (arr = []) => {
   const result = arr.map(obj => {
      const res = {};
      res[obj['user']] = obj['liked'];
      return res;
   });
   return result;
};
console.log(mapToPair(arr));

Output

And the output in the console will be −

[ { dan: 'yes' }, { sarah: 'no' }, { john: 'yes' } ]
raja
Published on 21-Nov-2020 06:50:27
Advertisements