- Using entries() Method to Convert JSON Object to JavaScript Array
- Using for-in Loop to Convert JSON Object to JavaScript Array
Method 1: Using entries() Method to Convert JSON Object to JavaScript Array
JavaScript provides the entries() method for converting the JSON object into an array. The method utilizes the Object class to perform the conversion. To use it, the syntax of the entries() method is provided below:
Syntax
In this syntax, “JSON_obj” specifies a JSON object that is to be converted into a JavaScript array.
Code
const teacher = {name: "Harry", age: 30, subject: "English"};
console.log(Object.entries(teacher));
The description of the code is as follows:
- Firstly, a JSON object “teacher” is created which comprises elements like “name”, “age”, and “subject”.
- The “entries()” method is utilized to perform conversion from JSON objects to JavaScript arrays. In this method, the JSON object “teacher” is passed as an argument to get the JavaScript array.
- Finally, the console.log() method is adapted to display the array in the browser.
Output
The output returns that the JSON object “teacher” is converted to an array.
Method 2: Using a “for-in” Loop to Convert JSON Object to JavaScript Array
Another method is considered through a for-in loop to convert the JSON object to a JavaScript array. The for-in loop iterates over the JSON object. Each iteration returns a key value that is helpful in converting the object to an array in JavaScript. For instance, the code is given below:
Code
var json_obj = {"John":10,"Harry":17};
var array = [];
for(var i in json_obj)
array.push([i, json_obj[i]]);
console.log(json_obj);
console.log(array);
The description of the code is as follows:
- Firstly, a JSON object “json_obj” is initialized with two elements “John” and “Harry”.
- Furthermore, an empty “array” is initialized that stores the elements of the JSON object.
- After that, a “for in loop” is employed that executes the number of elements in the “json_obj”.
- In this loop, the array.push() method is utilized to insert the elements from “json_obj” into the array.
Output
The output shows that the JSON object “json_obj” is converted to a JavaScript “array” by utilizing the “for-in loop”.
Conclusion
JavaScript provides “entries()” and “for-in loop” to convert the JSON object to a JavaScript array. The entries() method is employed to perform the conversion from a JSON object to an array using the object class. Moreover, a for-in loop works on an empty array to store the elements of the JSON object in the array. In this post, both methods are explained with the help of examples to convert JSON objects into an array.