我有以下对象
0:Object
April:2055.78
August:2511.18
December:1833.21
February:2605.03
January:1964.85
July:2337.65
June:2417.68
March:1953.51
May:2203.28
November:2433.3
October:1600.67
September:1874.85
我需要数组中对象的值,但是需要按月排序,Jan->分解
尝试过几种不同的方法,但仍然无法获得正确的结果。
提前致谢
答案 0 :(得分:1)
obj={
April:2055.78,
August:2511.18,
December:1833.21,
February:2605.03,
January:1964.85,
July:2337.65,
June:2417.68,
March:1953.51,
May:2203.28,
November:2433.3,
October:1600.67,
September:1874.85
};
console.log(["January","February","March","April","May","June","July","August","September","October","November","December"].map(month=>obj[month]));
Theres没有其他方法让引擎知道如何排序(除了时间昂贵的日期解析),你只能告诉它确切的月份顺序......
答案 1 :(得分:1)
我就这样做了:我创建了一个带有缩写月份名称的有序数组。然后我按顺序循环遍历该数组,如果数组值是对象键的子字符串,那么我将该键值对推入一个新对象。打印对象键时,它会按顺序打印出来。
var m = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];
var obj = {
April:2055.78,
August:2511.18,
December:1833.21,
February:2605.03,
January:1964.85,
July:2337.65,
June:2417.68,
March:1953.51,
May:2203.28,
November:2433.3,
October:1600.67,
September:1874.85
};
var ordered = {};
for(var i = 0; i < m.length; i++){
for(key in obj){
if(key.includes(m[i])){
ordered[key] = obj[key];
break;
}
}
}
for(key in ordered){
console.log(key);
}
答案 2 :(得分:1)
您可以使用简单的forEach
和数月的数组来执行此操作:
var months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
var results = [];
months.forEach(function(month){
results.push(obj[month]);
});
<强>演示:强>
var months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
var obj={
April:2055.78,
August:2511.18,
December:1833.21,
February:2605.03,
January:1964.85,
July:2337.65,
June:2417.68,
March:1953.51,
May:2203.28,
November:2433.3,
October:1600.67,
September:1874.85
};
var results = [];
months.forEach(function(month){
results.push(obj[month]);
});
console.log(results);
答案 3 :(得分:0)
假设您只想要几个月而不是值:
将您的对象放入变量(可选)
var months = {the months object}
然后将密钥提取到数组中并进行排序。
var sortedMonths = Object.keys(months).sort()