I got an array from a CMS that is poorly formatted which I want to reformat to an array of objects.
let daysOffArray = ["2022-08-22, 08:00 - 14:00","2022-08-23, 08:00 - 13:00"];
Expected result after separating the array:
let daysOff = [{
date: "2022-08-22",
time: 08:00 - 14:00
},
{
date: "2022-08-23",
time: 08:00 - 13:00
}];
How can I separate the array for each second comma and then separate the two new arrays after each comma?
CodePudding user response:
let daysOffArray = ["2022-08-22, 08:00 - 14:00","2022-08-23, 08:00 - 13:00"];
let daysOff=[]
daysOffArray.map((item)=>{
daysOff.push({date:item.split(",")[0],time:item.split(",")[1]})
})
console.log(daysOff)
CodePudding user response:
Use String#split
and Array#map
:
let daysOff = daysOffArray.map(i => {
const data = i.split(", "):
return { date: data[0], time: data[1] };
});
CodePudding user response:
// Initial object
var daysOffArray = [
'2022-08-22, 08:00 - 14:00',
'2022-08-23, 08:00 - 13:00',
];
// An empty array for the formatted object
var daysOffFormatted = [];
// Splitting and formatting the array
daysOffArray.forEach((daysOff) => {
var date = daysOff.split(',')[0].trim();
var time = daysOff.split(',')[1].trim();
// Adding formatted object to the array
daysOffFormatted.push({ date, time });
});
console.log(daysOffFormatted);
CodePudding user response:
let daysOff = daysOffArray.map((datetime)=>{
const [date, time] = datetime.split(',');
return {date, time: time.trim()};
});