如果我的对象的商店信息看起来像这样。
storeHours:
0:
day: Sunday
Open: 9:00am
close: 6:00pm
0:
day: Monday
Open: 8:00am
close: 10:00pm
0:
day: Tuesday
Open: 8:00am
close: 10:00pm
0:
day: Wednesday
Open: 8:00am
close: 10:00pm
0:
day: Thursday
Open: 8:00am
close: 10:00pm
0:
day: Friday
Open: 8:00am
close: 10:00pm
0:
day: Saturday
Open: 9:00am
close: 6:00pm
我应该写什么函数来获得能够给我的输出
simplestoreHours:
0:
Days: Monday-Friday
open: 8:00am
close: 6:00pm
1:
Days: Saturday-Sunday
open: 9:00am
close: 6:00pm
同样,所有时间都是格式化的momentjs对象,因此可以使用momentjs。
我最初的想法是做一个循环并让每个元素相互检查。如果打开和关闭时间相同,那么只需连接日期,但我认为这不是很聪明。
答案 0 :(得分:1)
reduce
数组方法可以帮助你。
在最后一次迭代中,我们可以通过范围键查找天数,查找天数,对其进行排序,创建Days属性作为分区首先和最后排序天数组并保存组合对象。
var groupedObject = obj.reduce(function (memo, item, i, array) {
var key = item.open+item.close;
memo.ranges[key] = memo.ranges[key] || {};
memo.days[key] = memo.days[key] || [];
memo.ranges[key] = { open: item.open, close: item.open };
memo.days[key].push({
index: ['mon', 'tue', 'wed', 'thu', 'fri', 'sat', 'sun'].indexOf(item.day),
name: item.day
})
if (i == array.length-1 ) {
for (var key in memo.ranges) {
if (memo.ranges.hasOwnProperty(key)) {
memo.days[key].sort(function(a,b) { return a.index - b.index });
memo.grouped.push({
Days: [
memo.days[key][0].name,
memo.days[key][memo.days[key].length-1 ].name
].join('-'),
open: memo.ranges[key].open,
close: memo.ranges[key].close
});
}
}
}
return memo
}, { ranges: {}, days: {}, grouped: [] });
console.log(groupedObject.grouped);
多数民众赞成)
答案 1 :(得分:0)
你可以这样做:
var storeHours = [
{day: 'Sunday', open: '9:00am', close: '6:00pm' },
{day: 'Monday', open: '8:00am', close: '10:00pm' },
{day: 'Tuesday', open: '8:00am', close: '10:00pm' },
{day: 'Wednesday', open: '8:00am', close: '10:00pm' },
{day: 'Thursday', open: '8:00am', close: '10:00pm' },
{day: 'Friday', open: '8:00am', close: '10:00pm' },
{day: 'Saturday', open: '9:00am', close: '6:00pm' }
];
function sort() {
var daysSorted = [];
for (var dayCounter = 0, length = storeHours.length; dayCounter < length; dayCounter++) {
var open = storeHours[dayCounter].open,
close = storeHours[dayCounter].close,
name = storeHours[dayCounter].day,
found = false;
for (var sortedDayCounter = 0, lengthSorted = daysSorted.length; sortedDayCounter < lengthSorted; sortedDayCounter++) {
var sortedOpen = daysSorted[sortedDayCounter].open,
sortedClose = daysSorted[sortedDayCounter].close;
if (sortedOpen === open && sortedClose == close) {
daysSorted[sortedDayCounter].day += ', ' + name;
found = true;
}
};
if (!found) {
daysSorted.push(storeHours[dayCounter]);
}
};
return daysSorted;
}
console.log(sort());
无论如何,我建议你考虑打开和关闭日期作为日期类型,而不是字符串。
希望这有帮助,