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

From JSON object to an array in JavaScript


We are required to create an array out of a JavaScript object, containing the values of all of the object's properties.

For example, given this object −

{
   "firstName": "John",
   "lastName": "Smith",
   "isAlive": "true",
   "a
}

We have to produce this array −

const myarray = ['John', 'Smith', 'true', '25'];

Therefore, let’s write the code for this function −

Example

The code for this will be −

const obj = {
   "firstName": "John",
   "lastName": "Smith",
   "isAlive": "true",
   "age": "25"
};
const objectToArray = obj => {
   const keys = Object.keys(obj);
   const res = [];
   for(let i = 0; i < keys.length; i++){
      res.push(obj[keys[i]]);
   };
   return res;
};
console.log(objectToArray(obj));

Output

The output in the console will be −

[ 'John', 'Smith', 'true', '25' ]

Output

Another Solution: One line alternate −

const obj = {
   "firstName": "John",
   "lastName": "Smith",
   "isAlive": "true",
   "age": "25"
};
const res = Object.values(obj);
console.log(res);