4 回答
TA贡献1866条经验 获得超5个赞
我的尝试
<script>
var array = [{
"heure1": "14:00",
"heure2": "17:00",
"DAY": "Sunday",
},
{
"heure1": "08:00",
"heure2": "13:00",
"DAY": "Sunday",
},
{
"heure1": "14:00",
"heure2": "16:00",
"DAY": "Monday",
},
{
"heure1": "08:00",
"heure2": "18:00",
"DAY": "Monday",
},
];
var days = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Sunday", "Saturday"];
var result = [];
days.map(function (day) {
var daysInArray = array.filter(function (a) {
return day == a.DAY
})
// console.log(daysInArray);
if (daysInArray.length) {
time = [];
daysInArray.map(function (item, i) {
for (var key in item) {
if (daysInArray[0].hasOwnProperty(key) && key != "DAY") {
time.push(item[key])
}
}
})
result.push({
"day": day,
"heure": time
})
} else {
result.push({
"day": day,
"heure": []
})
}
})
console.log(result);
</script>
TA贡献2012条经验 获得超12个赞
您可以先为一周的 7 天创建 7 个条目,每个条目的heure属性都有一个空数组。
然后迭代原始数据,查找正确的条目,将两次推入heure数组。
请注意,您的Day属性在示例输入中有不同的拼写(DAY、Day)。我强烈建议对此类属性名称使用全部小写字母。
这是一个实现:
var array = [{"heure1": "14:00","heure2": "17:00","day": "Sunday",}, {"heure1": "08:00","heure2": "13:00","day": "Sunday",}, {"heure1": "14:00","heure2": "16:00","day": "Monday",}, {"heure1": "08:00","heure2": "18:00","day": "Monday", },];
let days = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"];
let obj = Object.fromEntries(days.map(day => [day, { heure: [], day }]));
for (let {heure1, heure2, day} of array) obj[day].heure.push(heure1, heure2);
let result = Object.values(obj);
console.log(result);
TA贡献1777条经验 获得超10个赞
我的方式...
var arr_1 =
[ { heure1: '14:00', heure2: '17:00', day: 'Sunday' }
, { heure1: '08:00', heure2: '13:00', day: 'Sunday' }
, { heure1: '14:00', heure2: '16:00', day: 'Monday' }
, { heure1: '08:00', heure2: '18:00', day: 'Monday' }
]
const days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday']
const res = days.map(d=>
{
let r = { heure:[], day:d }
arr_1.filter(x=>x.day===d)
.forEach(({heure1,heure2})=> { r.heure.push(heure1,heure2) })
r.heure.sort()
return r
})
console.log( res )
.as-console-wrapper { max-height: 100% !important; top: 0; }
TA贡献1876条经验 获得超7个赞
那个结果结构是必要的吗?
如果不是,修改结果结构,你可以这样做:
const getHeureByDay = (heureArray) => {
let result = {
Sunday: { heure: [] },
Monday: { heure: [] },
Tuesday: { heure: [] },
Wednesday: { heure: [] },
Thursday: { heure: [] },
Friday: { heure: [] },
Saturday: { heure: [] },
};
heureArray.forEach((heureItem) => {
Object.keys(heureItem).forEach((key) => {
if (key !== "day") {
result[heureItem.day].heure.push(heureItem[key]);
}
})
});
return result;
};
const heureArray = [
{
"heure1": "14:00",
"heure2": "17:00",
"day": "Sunday",
},
{
"heure1": "08:00",
"heure2": "13:00",
"day": "Sunday",
},
{
"heure1": "14:00",
"heure2": "16:00",
"day": "Monday",
},
{
"heure1": "08:00",
"heure2": "18:00",
"day": "Monday",
}
];
console.log(getHeureByDay(heureArray));
添加回答
举报