gpt4 book ai didi

javascript - 循环 JSON 并比较时间

转载 作者:行者123 更新时间:2023-11-28 06:00:30 24 4
gpt4 key购买 nike

我想要完成的是循环遍历这个 JSON,并比较“start_time”和“end_time”以确保时间不重叠。我在实现这个时遇到了麻烦。

我发现了这个:validate two times但它没有任何意义,也没有使用 JSON,但它是我发现的最接近的。我可以使用 jQuery 来做到这一点吗?

{
"Line_1":{
"artist":"Audien",
"day":"1",
"start_time":"13:00",
"end_time":"14:00",
"stage":"main"
},
"Line_2":{
"artist":"Slushii",
"day":"1",
"start_time":"13:30",
"end_time":"14:30",
"stage":"eclipse"
},
"Line_3":{
"artist":"DJ Snake",
"day":"1",
"start_time":"15:00",
"end_time":"16:00",
"stage":"main"
},
"Line_4":{
"artist":"Marshmello",
"day":"2",
"start_time":"14:15",
"end_time":"15:15",
"stage":"horizon"
}
}

预期输出:

Audien & Slushii Conflict!

DJ Snake Does not Conflict with anyone!

Marshmello Does not Conflict with anyone!

*通知第 1 天和第 2 天

最佳答案

这是一个相当冗长的原型(prototype),供您学习之用。它使用moment.jstwix.js .

演示: https://jsfiddle.net/JAAulde/5v7yksk3/4/

原型(prototype)代码的 HTML:

<ul id="output"></ul>

原型(prototype)代码的 JS

var data = {
"Line_1":{
"artist":"Audien",
"day":"1",
"start_time":"13:00",
"end_time":"14:00",
"stage":"main"
},
"Line_2":{
"artist":"Slushii",
"day":"1",
"start_time":"13:30",
"end_time":"14:30",
"stage":"eclipse"
},
"Line_3":{
"artist":"DJ Snake",
"day":"1",
"start_time":"15:00",
"end_time":"16:00",
"stage":"main"
},
"Line_4":{
"artist":"Marshmello",
"day":"2",
"start_time":"14:15",
"end_time":"15:15",
"stage":"horizon"
}
},
tmp_day = '2000-01-01',
outer_key,
outer,
inner_key,
inner,
tmp_range,
checked = {},
conflict_found = {},
conflicts = [],
i;

for (outer_key in data) {
if (Object.prototype.hasOwnProperty.call(data, outer_key)) {
outer = data[outer_key];

tmp_range = moment(tmp_day + 'T' + outer.start_time).twix(tmp_day + 'T' + outer.end_time);

checked[outer_key] = true;

for (inner_key in data) {
if (Object.prototype.hasOwnProperty.call(data, inner_key) &&
outer_key !== inner_key &&
!checked[inner_key]
) {
inner = data[inner_key];

if (outer.day === inner.day &&
(
tmp_range.contains(tmp_day + 'T' + inner.start_time) ||
tmp_range.contains(tmp_day + 'T' + inner.end_time)
)
) {
conflict_found[outer_key] = true;
conflict_found[inner_key] = true;

conflicts.push([
outer_key,
inner_key
]);
}
}
}
}
}

// Output:
document.getElementById('output').innerHTML = '';

for (i = 0; i < conflicts.length; i++) {
document.getElementById('output').innerHTML += '<li><strong>' + data[conflicts[i][0]].artist + '</strong> conflicts with <strong>' + data[conflicts[i][1]].artist + '</strong></li>';
}

for (outer_key in data) {
if (Object.prototype.hasOwnProperty.call(data, outer_key) &&
!conflict_found[outer_key]
) {
document.getElementById('output').innerHTML += '<li><strong>' + data[outer_key].artist + '</strong> does not conflict with anyone</li>';
}
}

关于javascript - 循环 JSON 并比较时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37313001/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com