Computer >> Computer tutorials >  >> Programming >> Javascript

Retrieve key and values from object in an array JavaScript


We are required to write a JavaScript function that takes in an object that maps literal values. The function should create an array of array, each subarray should contain exactly two elements.

The first of which should be the key of corresponding object pair and second should be the value.

Example

const obj = {
   name: 'Nick',
   achievements: 158,
   points: 14730
};
const retrieveProperties = (obj = {}) => {
   const res = [];
   for(key in obj){
      res.push([ key, obj[key] ]);
   };
   return res;
};
console.log(retrieveProperties(obj));

Output

And the output in the console will be −

[ [ 'name', 'Nick' ], [ 'achievements', 158 ], [ 'points', 14730 ] ]