Sorting Object by sub-object property

后端 未结 3 1277
灰色年华
灰色年华 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 18:55

    Properties (keys) of an object are not intrinsically ordered; you must maintain your own array of their ordering if you wish to do so.

    Here is an example of how you could simplify ordering your sample object by arbitrary properties via custom sort functions:

    var orderKeys = function(o, f) {
      var os=[], ks=[], i;
      for (i in o) {
        os.push([i, o[i]]);
      }
      os.sort(function(a,b){return f(a[1],b[1]);});
      for (i=0; i<os.length; i++) {
        ks.push(os[i][0]);
      }
      return ks;
    };
    
    orderKeys(sample, function(a, b) {
      return a.age - b.age;
    }); // => ["Elem4", "Elem2", "Elem1", "Elem3"]
    
    orderKeys(sample, function(a, b) {
      return a.title.localeCompare(b.title);
    }); // => ["Elem2", "Elem1", "Elem4", "Elem3"]
    

    Once the properties are ordered as you like then you can iterate them and retrieve the corresponding values in order.

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-06 19:22

    Well, you can't sort a hashmap. : )

    However, here is a very simple sort, if you had an actual array.

    var sample = [{title:'Developer', age:33}, ...  etc  ];
    
    function ageSorter(a,b)
    {
       return ((a.age) < (b.age)) ? 1 : -1;
    }
    
    sample.sort(ageSorter);
    
    0 讨论(0)
提交回复
热议问题