Converting JavaScript object with numeric keys into array

Converting JavaScript object with numeric keys into array

I have an object like this coming back as a JSON response from the server:

I want to convert it into a JavaScript array like this:

Is there a best way to do this? Wherever I am reading, people are using complex logic using loops. So are there alternative methods to doing this?


Solution 1:

It’s actually very straight forward with jQuery’s $.map

var arr = $.map(obj, function(el) { return el });


and almost as easy without jQuery as well, converting the keys to an array and then mapping back the values with

var arr = Object.keys(obj).map(function(k) { return obj[k] });


That’s assuming it’s already parsed as a javascript object, and isn’t actually JSON, which is a string format, in that case a run through JSON.parse would be necessary as well.

In ES2015 there’s Object.values to the rescue, which makes this a breeze

var arr = Object.values(obj);

Solution 2:

var json = '{"0":"1","1":"2","2":"3","3":"4"}';

var parsed = JSON.parse(json);

var arr = [];

for(var x in parsed){

Hope this is what you’re after!

Related:  Calling Javascript using UIWebView

Solution 3:

You simply do it like

var data = {
    "0": "1",
    "1": "2",
    "2": "3",
    "3": "4"
var arr = [];
for (var prop in data) {


Solution 4:

There is nothing like a “JSON object” – JSON is a serialization notation.

If you want to transform your javascript object to a javascript array, either you write your own loop [which would not be that complex!], or you rely on underscore.js _.toArray() method:

var obj = {"0":"1","1":"2","2":"3","3":"4"};
var yourArray = _(obj).toArray();

Solution 5:

Nothing hard here. Loop over your object elements and assign them to the array

var obj = {"0":"1","1":"2","2":"3","3":"4"};
var arr = [];
for (elem in obj) {

Solution 6:

var JsonObj= {"0":"1","1":"2","2":"3","3":"4"};
var array = [];
for(var i in JsonObj) {
    if(JsonObj.hasOwnProperty(i) && !isNaN(+i)) {
        array[+i] = JsonObj[i];