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
Object to array - JavaScript
Converting an object to an array of key-value pairs is a common task in JavaScript. There are several built-in methods to achieve this transformation.
Sample Object
Let's start with this example object:
const obj = {
name: "Vikas",
age: 45,
occupation: "Frontend Developer",
address: "Tilak Nagar, New Delhi",
experience: 23,
salary: "98000"
};
Using Object.entries() (Recommended)
The simplest approach is using Object.entries(), which directly converts an object to an array of key-value pairs:
const obj = {
name: "Vikas",
age: 45,
occupation: "Frontend Developer"
};
const result = Object.entries(obj);
console.log(result);
[ [ 'name', 'Vikas' ], [ 'age', 45 ], [ 'occupation', 'Frontend Developer' ] ]
Using Object.keys() and map()
You can also use Object.keys() with map() for more control:
const obj = {
name: "Vikas",
age: 45,
experience: 23
};
const result = Object.keys(obj).map(key => [key, obj[key]]);
console.log(result);
[ [ 'name', 'Vikas' ], [ 'age', 45 ], [ 'experience', 23 ] ]
Manual Loop Approach
For educational purposes, here's a custom function using a for loop:
const obj = {
name: "Vikas",
age: 45,
salary: "98000"
};
const objectToArray = obj => {
const keys = Object.keys(obj);
const result = [];
for(let i = 0; i
[
[ 'name', 'Vikas' ],
[ 'age', 45 ],
[ 'salary', '98000' ]
]
Comparison
| Method | Performance | Code Length | Browser Support |
|---|---|---|---|
Object.entries() |
Fastest | Shortest | ES2017+ |
Object.keys() + map() |
Good | Medium | ES5+ |
| Manual loop | Good | Longest | All browsers |
Conclusion
Use Object.entries() for the cleanest and most efficient solution. It's the standard method for converting objects to key-value pair arrays in modern JavaScript.
Advertisements
