JavaScript排序多维对象 [英] Javascript sort multidimensional object

查看:40
本文介绍了JavaScript排序多维对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我知道这里有数十篇文章描述了如何对多维对象进行排序,但是我一直找不到适合我需求的文章.

So I know that there are dozens of posts on here that describe how to sort a multidimensional object, but I have not been able to find one that fits my needs.

所有这些解决方案都基于这样的对象:

All those solutions are based on an object like this:

[{id: 1, value: 'aaa'},{id: 40, value: 'bbbb'}]

我的对象看起来像这样:

My object looks like this:

buttons: {
    confirm: {
        class: 'btn btn-primary',
        value: 'Opslaan',
        order: 1
    },
    cancel: {
        class: 'btn btn-default',
        value: 'Annuleer',
        order: 10
    }
    delete: {
        class: 'btn btn-danger',
        value: 'Verwijder',
        order: 2
    }
},

自然,我想对它进行排序,以便结果是:确认,删除,取消. 我已经尝试过了(我预计不会起作用):

Naturally, I want to sort this so that the outcome is: confirm, delete, cancel. I have tried this (which I expected not to work):

this.options.buttons.sort ( function ( a, b ) {
    return a.order - b.order;
});

但这给了我Uncaught TypeError: undefined is not a function

非常感谢您的帮助!

推荐答案

正如@epascarello所述,JavaScript中没有针对对象的本机排序功能.

As @epascarello mentions, there is no native sort function for objects in JavaScript.

如果您有兴趣按照某种顺序对对象键的数组进行排序,则可以使用

If you are interested in sorting an array of your object's keys according to some order, you can use Object.keys()!

var buttons = {
  confirm: { value: 'foo', order: 0 },
  cancel: { value: 'bar', order: 2},
  delete: { value: 'baz', order: 1}
};

var sortedButtons = Object.keys(buttons).sort( function(keyA, keyB) {
  return buttons[keyA].order - buttons[keyB].order;
}); // returns ['confirm', 'delete', 'cancel']

这篇关于JavaScript排序多维对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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