如何排序javascript对象?

时间:2015-09-02 19:41:43

标签: javascript json

以下是我的目标:

var user1 = new Object();
user1.username = "user1"; user1.sex="m"; user1.age=20;

var user2 = new Object();
user2.username = "user1"; user2.sex="f";user2.age=30;

var user3 = new Object();
user3.username = "user3"; user3.sex="f";user3.age=22;

var users = {"john":user1, "jerry": user2, "marry":user3};

如何按年龄对用户进行排序?

1 个答案:

答案 0 :(得分:2)

首先,考虑将用户存储在数组中,而不是对象

var users = [user1, user2, user3];

然后你需要一个排序功能

//a and be will be passed in, you need to tell it which one is greater
function sortByAge(a,b) {

  if (a.age > b.age) return 1;
  if (a.age < b.age) return -1;
  /* else */ return 0;

  //how I had it previously that people commented on
  //return a.age > b.age;  
}

然后你可以在任何需要的地方使用那种

users.sort(sortByAge);