如何按工作日对工作日的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; });
谢谢.
就像我在评论中说的那样,你不能对一个对象进行排序,但是如果你可以改变你的数据格式以获得一个数组,你可以通过使用它轻松地对它进行排序 [].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) + "
");