Home >Web Front-end >JS Tutorial >How Can I Efficiently Convert Numeric-Keyed JSON Objects to Arrays in JavaScript?
Converting Numeric-Keyed Objects to Arrays
When working with JSON responses that include objects with numeric keys, you may encounter the need to convert them into arrays. While common solutions involve intricate loops, there are more efficient and straightforward approaches.
jQuery's $.map
One method utilizes jQuery's $.map function:
var arr = $.map(obj, function(el) { return el });
This method iterates over the object's properties and returns the corresponding values.
Array.map
Without jQuery, you can employ Array.map along with Object.keys:
var arr = Object.keys(obj).map(function(k) { return obj[k] });
Here, Object.keys converts the object's keys into an array and Array.map retrieves the values associated with those keys.
Object.values (ES2015)
In modern JavaScript (ES2015 and later), Object.values offers a succinct solution:
var arr = Object.values(obj);
This function directly returns an array of the object's values.
Note:
These methods assume the JSON response has already been parsed as a JavaScript object. If it's still in JSON string format, you'll need to use JSON.parse first:
var obj = JSON.parse(jsonString); var arr = Object.values(obj);
The above is the detailed content of How Can I Efficiently Convert Numeric-Keyed JSON Objects to Arrays in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!