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"]
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"]
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?
json_encode. It will only turn associative arrays into JSON objects and numerical indexed ones into arrays.if (!isNaN(+i)) {users_array[+i] = users[i]} may be better.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);