按属性名称对JavaScript对象进行排序

按属性名称对JavaScript对象进行排序

本文介绍了按属性名称对JavaScript对象进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在寻找一段时间,想要一种方法来对这样的Javascript对象进行排序:

I've been looking for a while and want a way to sort a Javascript object like this:

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

并按名称按字母顺序排序:

and sort is alphabetically by name to get:

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

我找不到任何可以执行此操作的代码。任何人都可以给我一些帮助吗?

I can't find any code that will do this. Can anyone give me some help?

推荐答案

根据定义,,因此您可能无法以面向未来的方式执行此操作。相反,您应该考虑在实际向用户显示对象时对这些键进行排序。无论如何它在内部使用的排序顺序并不重要。

By definition, the order of keys in an object is undefined, so you probably won't be able to do that in a way that is future-proof. Instead, you should think about sorting these keys when the object is actually being displayed to the user. Whatever sort order it uses internally doesn't really matter anyway.

按照惯例,大多数浏览器将按照添加顺序保留对象中键的顺序。所以,你可以这样做,但不要指望它总是有效:

By convention, most browsers will retain the order of keys in an object in the order that they were added. So, you could do this, but don't expect it to always work:

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

这篇关于按属性名称对JavaScript对象进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-06 04:38