工作日的对象如星期日

工作日的对象如星期日

本文介绍了工作日的对象如星期日,星期一,......,星期六的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How to sort Javascript object of week days by weekdays i.e Here, is JSON format of object:

 {"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"]}

其中key是day,即Wednesday。我想根据工作日的顺序(即周日,周一,周二等)对其进行排序。

where key is day i.e."Wednesday". I want to sort it based on order of weekdays i.e Sunday, Monday, Tuesday etc

预期输出为:

{ "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;
});

谢谢。

推荐答案

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

Like I said in my comment, you can't sort an object but if you can change your data's format to have an array, you can easily sort it by using [].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("<pre>" + JSON.stringify(data, null, 3) + "</pre>");

编辑

要订购你的对象的密钥按星期几,再次,使用风险自负

To "order" your object's keys by day of the week, again order is not guaranteed, use at your own risk

let data = {
  "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"]
};

const sorter = {
  "monday": 1,
  "tuesday": 2,
  "wednesday": 3,
  "thursday": 4,
  "friday": 5,
  "saturday": 6,
  "sunday": 7
};

let tmp = [];
Object.keys(data).forEach(function(key) {
  let value = data[key];
  let index = sorter[key.toLowerCase()];
  tmp[index] = {
    key: key,
    value: value
  };
});

let orderedData = {};
tmp.forEach(function(obj) {
  orderedData[obj.key] = obj.value;
});

console.log(orderedData);
document.write("<pre>" + JSON.stringify(orderedData, null, 3) + "</pre>");

这篇关于工作日的对象如星期日,星期一,......,星期六的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-24 01:12