按子对象属性排序对象 [英] Sorting Object by sub-object property

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

问题描述

我有一个物体的物体,我想根据物业进行排序......在缠绕它时遇到一些麻烦:

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

我的预期结果将是一个对象,其键现在已订购Elem4,Elem2,Elem1,Elem3。或者,我可以简单地按顺序返回键,而不是物理地对对象进行排序。

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.

这是否比它的价值更麻烦,或者我错过了一些显而易见(或不那么明显)的JavaScript-Fu可以轻松完成这样的工作吗?

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?

谢谢!

推荐答案

对象的属性(键)本质上不是有序的;如果你愿意,你必须维护自己的排序数组。

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.

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

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