Home > Web Front-end > JS Tutorial > body text

How to Sort a JavaScript Object Alphabetically by Property Name?

DDD
Release: 2024-11-01 18:14:30
Original
493 people have browsed it

How to Sort a JavaScript Object Alphabetically by Property Name?

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'
}
Copy after login

Result:

{
    api_key: 'fa3af76b9396d0091c9c41ebe3c63716',
    artist: 'Green Day',
    format: 'json',
    method: 'artist.getInfo'
}
Copy after login

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;
}
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!