最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

convert json array to javascript array - Stack Overflow

programmeradmin1浏览0评论

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"]
Share Improve this question edited Apr 11, 2011 at 8:20 Marcel Jackwerth 54.8k9 gold badges76 silver badges88 bronze badges asked Apr 11, 2011 at 8:16 shasi kanthshasi kanth 7,09426 gold badges110 silver badges164 bronze badges 3
  • I also found this useful: stackoverflow.com/questions/4375537/… – shasi kanth Commented Apr 11, 2011 at 15:10
  • Can any tell me this is json array or json object? – Katty Commented Jan 19, 2017 at 6:13
  • @anil This might help: stackoverflow.com/a/12289961/386579 – shasi kanth Commented Jan 19, 2017 at 11:48
Add a comment  | 

3 Answers 3

Reset to default 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?

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)

  1. 暂无评论