我正在使用API,它正在以一种奇怪的格式向我分发数据。或者至少对我来说。数据是商店的营业时间,我希望以我在前端需要的方式匹配它们(应用程序是用Angular编写的,使用两个API,因此我需要让API使用我的逻辑,我不想去适应它们的格式)JavaScript:优化循环内部循环内部的循环
这是数据从API来的格式为:
var operatingHoursArray = [
{Weds: true, End: "17:00", Start: "09:00"},
{Tue: true, End: "17:00", Start: "09:00"},
{Thur: true, End: "17:00", Start: "09:00"},
{Sun: false, End: "", Start: ""},
{Sat: true, End: "17:00", Start: "09:00"},
{Mon: true, End: "17:00", Start: "09:00"},
{Fri: true, End: "17:00", Start: "09:00"}
]
一个奇怪的结构IMO,我会者优先一周的日子作为对象,然后将开放和关闭的时间藏在其中。 我的应用程序(AngularJS)需要的数据是按以下格式:
var formattedHours = {
Sunday: 'Closed',
Monday: 'Closed',
Tuesday: 'Closed',
Wednesday: 'Closed',
Thursday: 'Closed',
Friday: 'Closed',
Saturday: 'Closed'
};
时报默认为“关闭”,这是我使用一周中的一天,我需要它的格式相匹配的代码在:
var daysOfWeek = [
{ sform: 'Mon', lform: 'Monday' },
{ sform: 'Tue', lform: 'Tuesday' },
{ sform: 'Weds', lform: 'Wednesday' },
{ sform: 'Thur', lform: 'Thursday' },
{ sform: 'Fri', lform: 'Friday' },
{ sform: 'Sat', lform: 'Saturday' },
{ sform: 'Sun', lform: 'Sunday' }
];
// Loop through the operating hours for the dealer
for (var i = operatingHoursArray.length - 1; i >= 0; i--) {
// Loop through the property names for each day, getting the first property name (the day of week)
for (property in operatingHoursArray[i]) {
// Loop through the days of the week
for (var v = daysOfWeek.length - 1; v >= 0; v--) {
// If the day of the week (array) matches the property name, get the details
if(daysOfWeek[v].sform == property && operatingHoursArray[i][property] === true) {
formattedHours[daysOfWeek[v].lform] = operatingHoursArray[i].Start + ' - ' + operatingHoursArray[i].End;
}
};
break; // Forces loop to stop after first property
}
};
这是越来越真是可恶非常快,但我的知识(菜鸟级),我不能确定的是如何使这个任何更有效。它正在为我所需要的工作,但有没有更好的方法来编码?目前它必须运行49次以检查每周的每一天。另外,一些商店不提供7天的时间,而只提供他们开放的时间。我无法更改formattedHours
的结构,因为其他API依赖于相同的结构。
如果你打开具有长而不是短名称的最终目标可能是快了很多 – Markasoftware
'//强制循环停止第一property'后没有“第一个属性”。使用'for-in'时,您不能依赖迭代顺序。 –
Ooo,我不知道,谢谢你的抬头。如果他们不按顺序,那真的会搞砸了:S。 – Neil