i have a json array that i want to convert into a plain javascript array:
This is my json array:
var users = {"0":"John","1":"Simon","2":"Randy"}
How to convert it into a plain javascript array like this:
var users = ["John", "Simon", "Randy"]
Convert JSON to Array Using `json. The parse() function takes the argument of the JSON source and converts it to the JSON format, because most of the time when you fetch the data from the server the format of the response is the string. Make sure that it has a string value coming from a server or the local source.
Example - Parsing JSON Use the JavaScript function JSON.parse() to convert text into a JavaScript object: const obj = JSON.parse('{"name":"John", "age":30, "city":"New York"}'); Make sure the text is in JSON format, or else you will get a syntax error.
' { } ' used for Object and ' [] ' is used for Array in json.
Stringify a JavaScript ArrayUse the JavaScript function JSON.stringify() to convert it into a string. const myJSON = JSON.stringify(arr); The result will be a string following the JSON notation.
users
is already a JS object (not JSON). But here you go:
var users_array = [];
for(var i in users) {
if(users.hasOwnProperty(i) && !isNaN(+i)) {
users_array[+i] = users[i];
}
}
Edit: Insert elements at correct position in array. Thanks @RoToRa.
Maybe it is easier to not create this kind of object in the first place. How is it created?
Just for fun - if you know the length of the array, then the following will work (and seems to be faster):
users.length = 3;
users = Array.prototype.slice.call(users);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With