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
How to turn a JSON object into a JavaScript array in JavaScript ?
Converting a JSON object with numeric string keys into a JavaScript array is a common operation. This is particularly useful when dealing with API responses or data structures that use indexed properties.
The Problem
Consider this JSON object where index keys are mapped to string values:
const obj = {
"0": "Rakesh",
"1": "Dinesh",
"2": "Mohit",
"3": "Rajan",
"4": "Ashish"
};
console.log(typeof obj); // "object"
object
Method 1: Using Object.keys() and forEach()
This approach iterates through object keys and maps them to array indices:
const obj = {
"0": "Rakesh",
"1": "Dinesh",
"2": "Mohit",
"3": "Rajan",
"4": "Ashish"
};
const objectToArray = (obj) => {
const res = [];
const keys = Object.keys(obj);
keys.forEach(el => {
res[+el] = obj[el]; // Convert string key to number
});
return res;
};
console.log(objectToArray(obj));
[ 'Rakesh', 'Dinesh', 'Mohit', 'Rajan', 'Ashish' ]
Method 2: Using Object.values() (Simpler)
If the object keys are sequential starting from "0", use Object.values():
const obj = {
"0": "Rakesh",
"1": "Dinesh",
"2": "Mohit",
"3": "Rajan",
"4": "Ashish"
};
const objectToArray = (obj) => Object.values(obj);
console.log(objectToArray(obj));
[ 'Rakesh', 'Dinesh', 'Mohit', 'Rajan', 'Ashish' ]
Method 3: Using Array.from() with Object.values()
Explicitly create an array from object values:
const obj = {
"0": "Rakesh",
"1": "Dinesh",
"2": "Mohit"
};
const result = Array.from(Object.values(obj));
console.log(result);
console.log(Array.isArray(result)); // Verify it's an array
[ 'Rakesh', 'Dinesh', 'Mohit' ] true
Handling Non-Sequential Keys
For objects with gaps or non-sequential keys, use the first method:
const sparseObj = {
"0": "First",
"2": "Third",
"5": "Sixth"
};
const objectToArray = (obj) => {
const res = [];
Object.keys(obj).forEach(key => {
res[+key] = obj[key];
});
return res;
};
console.log(objectToArray(sparseObj));
console.log("Length:", objectToArray(sparseObj).length);
[ 'First', <1 empty item>, 'Third', <2 empty items>, 'Sixth' ] Length: 6
Comparison
| Method | Best For | Handles Gaps? |
|---|---|---|
Object.keys() + forEach |
Non-sequential keys | Yes |
Object.values() |
Sequential keys from "0" | No |
Array.from() |
Explicit array creation | No |
Conclusion
Use Object.values() for simple sequential conversion, or Object.keys() with forEach() when you need to handle non-sequential numeric keys and preserve array indices.
