当前位置:  开发笔记 > 编程语言 > 正文

工作日的对象如星期日,星期一,......,星期六

如何解决《工作日的对象如星期日,星期一,,星期六》经验,为你挑选了1个好方法。

如何按工作日对工作日的Javascript对象进行排序,即这里是对象的JSON格式:

 {"Friday":["5:00pm to 12:00am"] ,"Wednesday":["5:00pm to 11:00pm"],"Sunday":["11:00am to 11:00pm"], "Thursday":["5:00pm to 11:00pm"],"Saturday":["11:00am to 12:00am"]}

关键是日,即"星期三".我想根据工作日的顺序排序,即周日,周一,周二等

预期产出是:

{ "Wednesday":["5:00pm to 11:00pm"], "Thursday":["5:00pm to 11:00pm"], "Friday":["5:00pm to 12:00am"], "Saturday":["11:00am to 12:00am"], "Sunday":["11:00am to 11:00pm"]}

这就是我的尝试.

var keys = {}; 
Object.keys(scope.daySpecificHours)
.map(function (k) { return [k, scope.daySpecificHours[k]]; })
.sort(function (a, b) {
if (a[0] < b[0]) return -1;
if (a[0] > b[0]) return 1;
return 0;
})
.forEach(function (d) {
scope.daySpecificHours[d[0]] = d;
});

谢谢.



1> Shanoor..:

就像我在评论中说的那样,你不能对一个对象进行排序,但是如果你可以改变你的数据格式以获得一个数组,你可以通过使用它轻松地对它进行排序 [].sort

let data = [
  { day: "Friday", hours: ["5:00pm to 12:00am"] },
  { day: "Wednesday", hours: ["5:00pm to 11:00pm"] },
  { day: "Sunday", hours: ["11:00am to 11:00pm"] },
  { day: "Thursday", hours: ["5:00pm to 11:00pm"] },
  { day: "Saturday", hours: ["11:00am to 12:00am"] }
];

const sorter = {
  // "sunday": 0, // << if sunday is first day of week
  "monday": 1,
  "tuesday": 2,
  "wednesday": 3,
  "thursday": 4,
  "friday": 5,
  "saturday": 6,
  "sunday": 7
}

data.sort(function sortByDay(a, b) {
  let day1 = a.day.toLowerCase();
  let day2 = b.day.toLowerCase();
  return sorter[day1] - sorter[day2];
});

console.log(data);
document.write("
" + JSON.stringify(data, null, 3) + "
");
推荐阅读
云聪京初瑞子_617
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有