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",
"age": "25"
}
We have to produce this array −
const myarray = ['John', 'Smith', 'true', '25'];
Example
Following is the code −
Solution1
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
This will produce the following output in console −
[ 'John', 'Smith', 'true', '25' ]
Solution 2 − One line alternate −
const obj = {
"firstName": "John",
"lastName": "Smith",
"isAlive": "true",
"age": "25"
};
const res = Object.values(obj);
console.log(res);Output
This will produce the following output in console −
[ 'John', 'Smith', 'true', '25' ]