按属性名称对 JavaScript 对象进行排序 [英] Sorting a JavaScript object by property name

查看:39
本文介绍了按属性名称对 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?

推荐答案

来自评论的更新:

这个答案已经过时了.在 ES6 对象中,键现在是有序的.请参阅这个问题了解向上- 最新答案

This answer is outdated. In ES6 objects keys are now ordered. See this question for an up-to-date answer

根据定义,对象中键的顺序未定义,因此您可能将无法以面向未来的方式做到这一点.相反,您应该考虑在对象实际显示给用户时对这些键进行排序.无论如何,它内部使用的任何排序顺序都无关紧要.

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 对象进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆