Home >Web Front-end >JS Tutorial >How Can I Convert a JavaScript Object with Numeric Keys into an Array?
Converting JavaScript Objects with Numeric Keys to Arrays
When working with data returned from a server, it's common to encounter objects with numeric keys. Transforming these objects into arrays can be challenging. However, with the right approaches, this conversion can be accomplished with ease.
One efficient method is utilizing jQuery's $.map function. By leveraging $.map and providing a callback function to extract the values, you can effortlessly convert the object to an array:
var arr = $.map(obj, function(el) { return el });
For those not using jQuery, a similar solution can be achieved with JavaScript's built-in methods. First, convert the numeric keys into an array:
var keys = Object.keys(obj);
Then, utilize Array.map to create an array containing the values:
var arr = Object.keys(obj).map(function(k) { return obj[k] });
ES2015 offers an even more concise approach with Object.values:
var arr = Object.values(obj);
The above is the detailed content of How Can I Convert a JavaScript Object with Numeric Keys into an Array?. For more information, please follow other related articles on the PHP Chinese website!