Reputation: 4292
I'm starting with a text-area string in "HHMM-HHMM\nHHMM\nHHMM" format (hours and minutes). The desired output is an array of objects that key the 1st number to start: and the 2nd to end, like:
[
{
start: 0900,
end: 1000
},
{
start: 1200,
end: 1300
},
]
In the code below I have split the initial string by line so that they will appear as an array:
splitting_array = ["0900-1000", "1200-1300"]
Next I am trying to use array.map to map each string to a new array of objects mapped to start and end properties. My hangup is here, I can split the 1st and second number using the hypen but I do not know how to do the object property mappings (start: and end:) from there. Thanks for any suggestions.
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)
}
Upvotes: 3
Views: 7380
Reputation: 18923
Simple solution:
var splitting_array = ["0900-1000", "1200-1300"];
var result = [];
for(var i = 0; i< splitting_array.length;i++){
var startTime = splitting_array[i].split("-")[0];
var endTime = splitting_array[i].split("-")[1];
var obj = {};
obj["start"] = startTime;
obj["end"] = endTime;
result.push(obj);
}
console.log(result);
Upvotes: 3
Reputation: 7273
So String.split
returns an array of your strings split by (and not including) the split-string you pass in, so box[0]
is your start, and box[1]
would be your end. Then, you just need to return the object that is to be mapped to your string item.
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"}]
Upvotes: 8