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"]
Marcel Jackwerth
  • 53,948
  • 9
  • 74
  • 88
shasi kanth
  • 6,987
  • 24
  • 106
  • 158

3 Answers3

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?

Community
  • 1
  • 1
Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
  • 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. – shasi kanth Apr 11 '11 at 09: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. – Felix Kling Apr 11 '11 at 09: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. – RoToRa Apr 11 '11 at 09: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. – Felix Kling Apr 11 '11 at 09: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);
David Tang
  • 92,262
  • 30
  • 167
  • 149
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);
shasi kanth
  • 6,987
  • 24
  • 106
  • 158