开发者

convert json array to javascript array

开发者 https://www.devze.com 2023-02-23 06:23 出处:网络
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\"}

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 i开发者_开发技巧t 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?


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


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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号