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?
It's actually very straight forward with jQuery's $.map
const o = {"0":"1","1":"2","2":"3","3":"4"};
const arr = $.map(o, function(el) { return el; })
console.log(arr)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
and almost as easy without jQuery as well, converting the keys to an array and then mapping back the values with Array.map
const o = {"0":"1","1":"2","2":"3","3":"4"};
const arr = Object.keys(o).map(k => o[k]);
console.log(arr)
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, but only if your object doesn't have any gaps in the keys:
const o = {"0":"1","1":"2","2":"3","3":"4"};
const arr = Object.values(o);
console.log(arr);
If there are gaps, you'll want to use Object.entires
instead, and then reduce the key/value pairs to an array instead:
const o = {"0":"1","5":"6","7":"8","10":"11"};
const arr = Object.entries(o).reduce((arr, [key, value]) => {
arr[key] = value;
return arr;
}, []);
console.log(arr);