Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
How to convert an object into an array in JavaScript?
In JavaScript, there are several methods to convert an object into an array. The approach depends on whether you want the keys, values, or both from the object.
Using Object.keys() to Get Keys Array
The Object.keys() method returns an array of an object's property names:
const student = {
name: "Chris",
age: 25,
marks: 85,
city: "New York"
};
const keysArray = Object.keys(student);
console.log(keysArray);
[ 'name', 'age', 'marks', 'city' ]
Using Object.values() to Get Values Array
The Object.values() method returns an array of an object's property values:
const student = {
name: "Chris",
age: 25,
marks: 85,
city: "New York"
};
const valuesArray = Object.values(student);
console.log(valuesArray);
[ 'Chris', 25, 85, 'New York' ]
Using Object.entries() to Get Key-Value Pairs Array
The Object.entries() method returns an array of key-value pairs as nested arrays:
const student = {
name: "Chris",
age: 25,
marks: 85,
city: "New York"
};
const entriesArray = Object.entries(student);
console.log(entriesArray);
[ [ 'name', 'Chris' ], [ 'age', 25 ], [ 'marks', 85 ], [ 'city', 'New York' ] ]
Converting Array of Objects to Array of Values
For an array of objects, you can extract specific property values using map():
const studentDetails = [
{ studentName: "Chris", studentMarks: 34 },
{ studentName: "David", studentMarks: 89 },
{ studentName: "Sarah", studentMarks: 76 }
];
// Extract student names
const nameArray = studentDetails.map(student => student.studentName);
console.log(nameArray);
// Extract student marks
const marksArray = studentDetails.map(student => student.studentMarks);
console.log(marksArray);
[ 'Chris', 'David', 'Sarah' ] [ 34, 89, 76 ]
Comparison of Methods
| Method | Returns | Use Case |
|---|---|---|
Object.keys() |
Array of keys | When you need property names |
Object.values() |
Array of values | When you need property values |
Object.entries() |
Array of [key, value] pairs | When you need both keys and values |
Array.map() |
Array of specific values | For extracting from object arrays |
Conclusion
Use Object.keys(), Object.values(), or Object.entries() for single objects, and Array.map() for extracting values from object arrays. Choose the method based on what data you need from the object.
Advertisements
