简体   繁体   English

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

[英]How to sort the object based on array - javascript?

I have months values like below 我有如下几个月的值

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
    }

How to sort the objects based on the months array? 如何根据months数组对对象进行排序?

Try with: 尝试:

var output = [];

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

It will returns you ordered list of objects that contain name and value keys which have proper month name and its value. 它将返回包含有namevalue键的对象的有序列表,这些键具有正确的月份名称及其值。

var values = [];

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

This way you get the object properties' values ordered by the months array. 通过这种方式,您可以按months数组获得对象属性的值。

You can't sort the properties in an object, because the order of the properties is not maintained. 您无法对对象中的属性进行排序,因为不维护属性的顺序。 If create an object like that, then loop out the properties, you will see that the properties may not be returned in the same order that you put them in the object, and different browsers will return the properties in differend order. 如果创建这样的对象,然后循环出属性,您将看到属性返回的顺序可能与将其放入对象的顺序不同,并且不同的浏览器将以不同的顺序返回属性。

Make the object an array, so that it can maintain the order of the values, and make the lookup array an object so that you can efficiently map a string to a numeric value: 将对象设置为数组,以便可以保持值的顺序,将查找数组设置为对象,以便可以将字符串有效地映射为数值:

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

Now you can sort the array using the object: 现在,您可以使用对象对数组进行排序:

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM