让我向您展示我这里的一些工作代码:
有效的示例
[
{
"actual_time":"11:00:00",
"length":"30"
},
{
"actual_time":"13:05:00",
"length":"40"
}
]
var extracted_times = dataObj.map(o => o.actual_time.split(':').slice(0, 2).map(Number));
结果会是这样的:
[
[11, 0],
[13, 5]
]
所以效果很好。
<小时/>我的问题:
这是我遇到的问题。但如果我有这个怎么办:
[
{
"actual_time":"11:00:00",
"length":"30"
},
{
"actual_time":"13:05:00-00:40:00",
"length":"40"
}
]
如您所见,两个时间中间有一个破折号:13:05:00-00:40:00
。我该如何做到这一点,以便如果有破折号 -
,则执行如下操作:
我希望最终的结果是这样的:
[
[11, 0],
{ from: [13, 0], to: [0, 40] }
]
我怎样才能让它变成这样?谢谢!
最佳答案
var extracted_times = dataObj.map(function(obj){
// match all instances of the time string "hh:mm:ss"
var times = obj.actual_time.match(/\d\d:\d\d:\d\d/g)
// do your thing with the numbers
.map(t=>t.split(':').slice(0,2).map(Number));
// if there is only one, then return it
if(times.length == 1)
return times[0];
// if there are two, then return the object
return { from: times[0], to: times[1] };
});
关于javascript - 从 json 创建数组,但值有异常(exception),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55717276/