Converting JavaScript object with numeric keys into array

Nikhil Agrawal picture Nikhil Agrawal · Jan 2, 2014 · Viewed 673.5k times · Source

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

{"0":"1","1":"2","2":"3","3":"4"}

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

["1","2","3","4"]

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?

Answer

adeneo picture adeneo · Jan 2, 2014

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

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

FIDDLE

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

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

FIDDLE

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