How to turn a JSON object into a JavaScript array in JavaScript ?


Suppose, we have this JSON object where index keys are mapped to some literals −

const obj = {
   "0": "Rakesh",
   "1": "Dinesh",
   "2": "Mohit",
   "3": "Rajan",
   "4": "Ashish"
};

We are required to write a JavaScript function that takes in one such object and uses the object values to construct an array of literals.

Example

The code for this will be −

const obj = {
   "0": "Rakesh",
   "1": "Dinesh",
   "2": "Mohit",
   "3": "Rajan",
   "4": "Ashish"
};
const objectToArray = (obj) => {
   const res = [];
   const keys = Object.keys(obj);
   keys.forEach(el => {
      res[+el] = obj[el];
   });
   return res;
};
console.log(objectToArray(obj));

Output

And the output in the console will be −

[ 'Rakesh', 'Dinesh', 'Mohit', 'Rajan', 'Ashish' ]

Updated on: 20-Nov-2020

394 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements