Separate array after each second comma

Viewed 99

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 daysOffArray for each second comma and then separate the two new arrays after each comma?

5 Answers

Use String#split and Array#map:

let daysOff = daysOffArray.map(item => {
  const data = item.split(", ");
  return { date: data[0], time: data[1] };
});
  // 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);

You can use array destructuring and the object literal property value shorthand for a more concise solution and better readability.

daysOffArray.map(item => {
    const [date, time] = item.split(', ');
    return { date, time };
});
let daysOffArray = ["2022-08-22, 08:00 - 14:00","2022-08-23, 08:00 - 13:00"];

let daysOff = [];

daysOffArray.forEach((item) => {
  daysOff.push({ date: item.split(",")[0], time: item.split(",")[1] });
});

console.log(daysOff);
let daysOff = daysOffArray.map((datetime)=>{
    const [date, time] = datetime.split(',');
    return {date, time: time.trim()};
});
Related