- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Converting a JavaScript object to an array of values - 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", "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' ]
Advertisements
To Continue Learning Please Login
Login with Google