我从“HHMM-HHMM\nHHMM\nHHMM”格式(小时和分钟)的文本区域字符串开始。所需的输出是一个对象数组,其中第一个数字为开始:第二个数字为结束,例如:
[
{
start: 0900,
end: 1000
},
{
start: 1200,
end: 1300
},
]
在下面的代码中,我按行分割了初始字符串,以便它们显示为数组:
splitting_array = ["0900-1000", "1200-1300"]
接下来,我尝试使用 array.map 将每个字符串映射到映射到开始和结束属性的新对象数组。我的挂断就在这里,我可以使用连字符分割第一个和第二个数字,但我不知道如何从那里进行对象属性映射(开始:和结束:)。感谢您的任何建议。
var free_time_hours = document.getElementById('ftid')
free_time_hours.addEventListener("blur", save_free_time_hours)
function save_free_time_hours () {
// todo: break the new lines into array elements. Reset each time in case the user input updates
var splitting_array = free_time_hours.value.split(/\n/)
// todo: use the map function to map each string to an object with start and end properties
var split_objects = splitting_array.map(function(str) {
var box = str.split('-') // box[0] = 1200, box[1] = 1300
var obj = {}
// stuck here
})
// console.log("objectified start/end values")
// console.log(split_objects)
}
最佳答案
因此 String.split
返回一个由您传入的分割字符串分割(但不包括)的字符串数组,因此 box[0]
是您的开始,而 box[1]
将是你的结局。然后,您只需返回要映射到字符串项的对象即可。
var splitting_array = ["0900-1000", "1200-1300"];
var split_objects = splitting_array.map(function(str) {
var box = str.split('-');
return {start: box[0], end: box[1]}
});
console.log(split_objects); // [{start:"0900", end:"1000"}, {start:"1200", end:"1300"}]
关于javascript - 将字符串转换为对象数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44610550/