Sorting a JavaScript Object by Property Name
Q: How can I sort a JavaScript object like this alphabetically by property name?
{ method: 'artist.getInfo', artist: 'Green Day', format: 'json', api_key: 'fa3af76b9396d0091c9c41ebe3c63716' }
Result:
{ api_key: 'fa3af76b9396d0091c9c41ebe3c63716', artist: 'Green Day', format: 'json', method: 'artist.getInfo' }
A: Note that in ES6 and later, objects' keys are now ordered.
Previously, the order of keys in an object was undefined, making it difficult to sort an object consistently. Consider sorting the keys when the object is being displayed to users rather than relying on internal sort order.
However, if order is maintained, one way to sort an object by property name is:
function sortObject(o) { var sorted = {}, key, a = []; for (key in o) { if (o.hasOwnProperty(key)) { a.push(key); } } a.sort(); for (key = 0; key < a.length; key++) { sorted[a[key]] = o[a[key]]; } return sorted; }
The above is the detailed content of How to Sort a JavaScript Object Alphabetically by Property Name?. For more information, please follow other related articles on the PHP Chinese website!