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
Selected Reading
How to turn a JSON object into a JavaScript array in JavaScript ?
Suppose, we have this JSON object where index keys are mapped to some literals −
const obj = {
"0": "Rakesh",
"1": "Dinesh",
"2": "Mohit",
"3": "Rajan",
"4": "Ashish"
};
We are required to write a JavaScript function that takes in one such object and uses the object values to construct an array of literals.
Example
The code for this will be −
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];
});
return res;
};
console.log(objectToArray(obj));
Output
And the output in the console will be −
[ 'Rakesh', 'Dinesh', 'Mohit', 'Rajan', 'Ashish' ]
Advertisements
