gpt4 book ai didi

javascript - 检查具有相同 "rules"的多个变量

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:30:21 25 4
gpt4 key购买 nike

我必须构造一个对象数组。我可以“直接”完成,但我希望找到一种方法来遍历一些变量并在将它们“推”到数组中的正确位置时检查每个变量。

我有这个:

//this is the starting array...I'm going to update these objects
operationTime = [
{"isActive":false,"timeFrom":null,"timeTill":null},//Monday which is operationTime[0]
{"isActive":false,"timeFrom":null,"timeTill":null},
{"isActive":false,"timeFrom":null,"timeTill":null},
{"isActive":false,"timeFrom":null,"timeTill":null},
{"isActive":false,"timeFrom":null,"timeTill":null},
{"isActive":false,"timeFrom":null,"timeTill":null},
{"isActive":false,"timeFrom":null,"timeTill":null}
];

//I get the below via an API call
var monHours = placeHours.mon_open_close;
var tueHours = placeHours.tue_open_close;
var wedHours = placeHours.wed_open_close;
var thuHours = placeHours.thu_open_close;
var friHours = placeHours.fri_open_close;
var satHours = placeHours.sat_open_close;
var sunHours = placeHours.sun_open_close;
var sunHours = placeHours.sun_open_close;


//here's where I'm stuck.
if (monHours.length>0){
var arr = monHours[0].split("-");
operationTime[0].isActive= true;
operationTime[0].timeFrom= arr[0];
operationTime[0].timeTill= arr[1];
}
else {
operationTime[0].isActive= false;
}

我的 if/else 在上面的例子中使用星期一完美地工作,但我不想在一周的 7 天里写这个,让它变得不必要的复杂。我怎样才能将它压缩成一个单独的“函数”来测试每个变量并将其插入正确位置的数组对象中?

最佳答案

我想你可以把键放在一个数组中,然后使用 forEach 循环遍历 operationTime 并根据索引更新对象:

operationTime = [ 
{"isActive":false,"timeFrom":null,"timeTill":null},
{"isActive":false,"timeFrom":null,"timeTill":null},
{"isActive":false,"timeFrom":null,"timeTill":null},
{"isActive":false,"timeFrom":null,"timeTill":null},
{"isActive":false,"timeFrom":null,"timeTill":null},
{"isActive":false,"timeFrom":null,"timeTill":null},
{"isActive":false,"timeFrom":null,"timeTill":null}
];

// make an array of keys that has the same order of the operationTime
var keys = ['mon_open_close', 'tue_open_close', 'wed_open_close', 'thu_open_close', 'fri_open_close', 'sat_open_close', 'sun_open_close'];

var placeHours = {'mon_open_close': ['08:00-17:00'], 'tue_open_close':[], 'wed_open_close':[], 'thu_open_close':[], 'fri_open_close':[], 'sat_open_close':[], 'sun_open_close':['10:20-15:30']}

operationTime.forEach( (obj, index) => {
var dayHours = placeHours[keys[index]];
if(dayHours.length > 0) {
var arr = dayHours[0].split("-");
obj.isActive= true;
obj.timeFrom= arr[0];
obj.timeTill= arr[1];
}
})

console.log(operationTime);

关于javascript - 检查具有相同 "rules"的多个变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45449805/

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