8

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"]
3

3 Answers 3

9

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?

4
  • This 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. Commented Apr 11, 2011 at 9:03
  • 2
    @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. Commented Apr 11, 2011 at 9:10
  • 4
    Careful, 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. Commented Apr 11, 2011 at 9:37
  • @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. Commented Apr 11, 2011 at 9:46
4

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);
0
0

Well, here is a Jquery+Javascript solution, for those who are interested:

var user_list = [];

$.each( users, function( key, value ) {
    user_list.push( value );    
});

console.log(user_list);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.