convert json array to javascript array
27,053
Solution 1
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?
Solution 2
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);
Related videos on Youtube
Author by
shasi kanth
I am a Web Developer, Husband, Father and Singer. [I am #SOreadytohelp] When not doing work, I would spend time with meditation and music. My Developer Story
Updated on February 25, 2020Comments
-
shasi kanth about 4 years
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"]
-
shasi kanth about 13 yearsThis json array is created dynamically with Zend_Json::encode, but the response is passed back to a js function, that accepts a plain javascript array.
-
Felix Kling about 13 years@dskanth: If you are not doing anything fancy, use the native function
json_encode
. It will only turn associative arrays into JSON objects and numerical indexed ones into arrays. -
RoToRa about 13 yearsCareful, your code may not assign the values to the correct indexes, because you are assuming the object properties are iterated sorted.
if (!isNaN(+i)) {users_array[+i] = users[i]}
may be better. -
Felix Kling about 13 years@RoToRa: You are right. No I did not assume that they are sorted, but I didn't pay attention to the order... I will add this to my answer.