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


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' } ]

Updated on: 21-Nov-2020

512 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements