Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

convert json array to javascript array

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"]
like image 887
shasi kanth Avatar asked Apr 11 '11 08:04

shasi kanth


People also ask

Can we convert JSON to array?

Convert JSON to Array Using `json. The parse() function takes the argument of the JSON source and converts it to the JSON format, because most of the time when you fetch the data from the server the format of the response is the string. Make sure that it has a string value coming from a server or the local source.

How do you parse an array of JSON objects?

Example - Parsing JSON Use the JavaScript function JSON.parse() to convert text into a JavaScript object: const obj = JSON.parse('{"name":"John", "age":30, "city":"New York"}'); Make sure the text is in JSON format, or else you will get a syntax error.

What is [] and {} in JSON?

' { } ' used for Object and ' [] ' is used for Array in json.

Can I Stringify an array?

Stringify a JavaScript ArrayUse the JavaScript function JSON.stringify() to convert it into a string. const myJSON = JSON.stringify(arr); The result will be a string following the JSON notation.


2 Answers

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?

like image 80
Felix Kling Avatar answered Oct 27 '22 00:10

Felix Kling


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);
like image 24
David Tang Avatar answered Oct 27 '22 01:10

David Tang