Sorting Object by sub-object property

后端 未结 3 1295
灰色年华
灰色年华 2020-12-06 18:52

I have an object of objects, which I\'d like to sort by property... having some trouble wrapping my head around it:

sample = {
    \"Elem1\": { title: \"Deve         


        
3条回答
  •  悲哀的现实
    2020-12-06 19:15

    An Object in JavaScript has no order for properties; they may come in any order when iterated over (though in practice they usually come in the order they are defined).

    Use an Array, which has an explicit order, and the sort() method.

    If it were an Array, you could use...

    sample.sort(function(a, b) {
        return a.age - b.age;
    });
    

    jsFiddle.

提交回复
热议问题