Home >Web Front-end >JS Tutorial >How to Sort a JavaScript Object Alphabetically by Property Name?

How to Sort a JavaScript Object Alphabetically by Property Name?

DDD
DDDOriginal
2024-11-01 18:14:30569browse

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'
}

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!

Statement:
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