質問

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

But that gave me an Uncaught TypeError: undefined is not a function

Any help is much appreciated!

役に立ちましたか?

解決

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

他のヒント

I had a very similar need and I ended up doing something along these lines --

// Code typed on the fly -- untested.
buttons: {
    list: [],  // We'll store things here.
    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
    }
}


// Now, fill the list from the properties

for (var key in buttons) {
  // Don't actually use the 'list' property in the output
  if (key !== "list") {
    list.push(key);
  }
}

// Now that we have our list, sort it
// Any specialized sorting can be done in the `sort` method here
buttons.list = buttons.list.sort();

// Now, deal with the sorted list
for (var i = 0; i < buttons.list.length; i++) {
  var key = buttons.list[i];
  var button = buttons[key];
  console.log(button);
}
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top