Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
211 views
in Technique[技术] by (71.8m points)

javascript - Sorting Object by sub-object property

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: "Developer", age: 33 },
    "Elem2": { title: "Accountant", age: 24 },
    "Elem3": { title: "Manager", age: 53 },
    "Elem4": { title: "Intern", age: 18}
}

My expected result would be an object whose keys were now ordered Elem4, Elem2, Elem1, Elem3. Alternatively, I'd be fine with simply returning the keys in that order rather than physically sorting the object.

Is this more trouble than it's worth, or am I missing some obvious (or not-so-obvious) JavaScript-Fu that would make light work of something like this?

Thanks!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...