如何基于数组对对象进行排序-javascript?

时间:2013-09-19 09:13:54

标签: javascript

我有几个月的值,如下所示

var months = ["January","February","March","April","May","June","July","August","September","October","November","December"];

 var objects = {
        April:0,
        August:4182,
        December:0,
        February:0,
        January:1,
        July:2,
        June:0,
        March:0,
        May:0,
        November:0,
        October:0,
        September:1518
    }

如何根据月份数组对对象进行排序?

3 个答案:

答案 0 :(得分:2)

尝试:

var output = [];

for (var k in months) {
  var month = months[k];
  output.push({name: month, value: objects[month]});
}

它将返回包含namevalue个键的有序对象列表,这些键具有正确的月份名称及其值。

答案 1 :(得分:1)

var values = [];

for(var i = 0; i < months.length; i++) {
    vals.push(objects[months[i]]);
}

通过这种方式,您可以获得按月数组排序的对象属性值。

答案 2 :(得分:0)

您无法对对象中的属性进行排序,因为不会维护属性的顺序。如果创建这样的对象,然后循环输出属性,您将看到属性可能不会按照将它们放入对象的顺序返回,并且不同的浏览器将以不同的顺序返回属性。

使对象成为一个数组,以便它可以维护值的顺序,并使查找数组成为一个对象,以便您可以有效地将字符串映射到数值:

var months = {
  January: 1,
  February: 2,
  March: 3,
  April: 4,
  May: 5,
  June: 6,
  July: 7,
  August: 8,
  September: 9,
  October: 10,
  November: 11,
  December: 12
};

var objects = [
  { name: 'April', value: 0 },
  { name: 'August', value: 4182 },
  { name: 'December', value: 0 },
  { name: 'February', value: 0 },
  { name: 'January', value: 1 },
  { name: 'July', value: 2 },
  { name: 'June', value: 0 },
  { name: 'March', value: 0 },
  { name: 'May', value: 0 },
  { name: 'November', value: 0 },
  { name: 'October', value: 0 },
  { name: 'September', value: 1518 }
];

现在您可以使用对象对数组进行排序:

objects.sort(function(x,y) { return months[x.name] - months[y.name]; });

演示:http://jsfiddle.net/7eKfn/