-1

我有如下月份的值

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
    }

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

4

3 回答 3

2

尝试:

var output = [];

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

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

于 2013-09-19T09:16:16.037 回答
1
var values = [];

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

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

于 2013-09-19T09:21:24.707 回答
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/

于 2013-09-19T09:23:48.863 回答