根据某些条件修改JS数组

时间:2018-06-12 09:17:15

标签: javascript jquery



var arr = [{"Event_code":"AB-001","Interest_area":"Arts","Start_time":"9:00 AM","End_time":"3:00 PM","Session_type":"Course information session"},{"Event_code":"AB-002","Interest_area":"Arts","Start_time":"12:30 PM","End_time":"1:00 PM","Session_type":"Course information session"},{"Event_code":"AB-003","Interest_area":"","Start_time":"9:00 AM","End_time":"3:00 PM","Session_type":"Course information session"},{"Event_code":"AB-004","Interest_area":"Business","Start_time":"10:30 AM","End_time":"11:00 AM","Session_type":"Course information session"},{"Event_code":"AB-005","Interest_area":"General Interest","Start_time":"9:00 AM","End_time":"1:30 PM","Session_type":"Experience"},{"Event_code":"AB-006","Interest_area":"Environment ,    Business       ","Start_time":"11:00 AM","End_time":"11:30 AM","Session_type":"Course information session"}];
var st = {};
arr.forEach(o => {
  if(st[o.Start_time]) o.clash = "yes";
  else st[o.Start_time] = o.Start_time;
  var diff = ( new Date("1970-1-1 " + o.End_time) - new Date("1970-1-1 " + o.Start_time) ) / 1000 / 60 / 60;
    //console.log(diff); // hours
    if (diff > 5){
        o.duration = "Full day event"; 
    }
});
console.log(arr);




我想要做的是根据2个条件添加2个键值对。

Cond 1.添加" Clash":"是" 如果2个事件具有相同的开始时间

Cond 2:添加"持续时间:"全天活动" if"开始时间"和#34;结束时间"差异超过5小时。

以上代码不打印"冲突":"是"对

This问题对条件1有很大帮助。我只想现在添加条件2。

2 个答案:

答案 0 :(得分:0)

要设置clash,您可以使用开始时间和实际索引来获取对象。

如果此时开始另一个事件,请将clash设置为两个对象。



var array = [{ Event_code: "AB-001", Interest_area: "Arts", Start_time: "9:00 AM", End_time: "3:00 PM", Session_type: "Course information session" }, { Event_code: "AB-002", Interest_area: "Arts", Start_time: "12:30 PM", End_time: "1:00 PM", Session_type: "Course information session" }, { Event_code: "AB-003", Interest_area: "", Start_time: "9:00 AM", End_time: "3:00 PM", Session_type: "Course information session" }, { Event_code: "AB-004", Interest_area: "Business", Start_time: "10:30 AM", End_time: "11:00 AM", Session_type: "Course information session" }, { Event_code: "AB-005", Interest_area: "General Interest", Start_time: "9:00 AM", End_time: "1:30 PM", Session_type: "Experience" }, { Event_code: "AB-006", Interest_area: "Environment, Business", Start_time: "11:00 AM", End_time: "11:30 AM", Session_type: "Course information session" }],
    clash = Object.create(null);

array.forEach((o, i, a) => {
    var diff = (new Date("1970-1-1 " + o.End_time) - new Date("1970-1-1 " + o.Start_time)) / 1000 / 60 / 60;
    //console.log(diff); // hours
    if (diff > 5) {
        o.duration = "Full day event";
    }

    if (o.Start_time in clash) {
        a[clash[o.Start_time]].clash = true; // set first found
        o.clash = true;                      // set actual item
        return;
    }
    clash[o.Start_time] = i;                 // save index
});

console.log(array);

.as-console-wrapper { max-height: 100% !important; top: 0; }




答案 1 :(得分:-1)

我稍微更改了您的代码,这是新的工作code