I have an object with multiple tasks. The challenge is to sort them into separate objects which I have managed to do with the code that follows. I would like to know how this can be adjusted to a state where the loop will sort the tasks without having to program it separately (Like a i++ sort of function). Any ideas how to accomplish this?
const tasks = {
title1: "Quiet Time",
title2: "Study",
title3: "Go Jogging",
title4: "Eat Breakfast",
description1: "",
description2: "",
decription3: "This is going to help to reach my goals and my life to the fullest",
decription4: "",
date1: "05/02/2020",
date2: "01/02/2020",
date3: "tomorrow",
date4: "today",
time1: "08:12",
time2: "13:15",
time3: "12:36",
time4: "13:25",
completed1: false,
completed2: true,
completed3: false,
completed4: true,
priority1: "red",
priority2: "yellow",
priority3: "black",
priority4: "white",
tags1: ["Personal", "Work", "School"],
tags2: ["Personal", "School", "Diary Entry"],
tags3: ["Content Creation", "Personal"],
tags4: ["Personal"]
}
const task1 = {};
const task2 = {};
const task3 = {};
const task4 = {};
for (let [key, value] of Object.entries(tasks)) {
if (key.endsWith('1')) {
task1[key] = value;
}
if (key.endsWith('2')) {
task2[key] = value;
}
if (key.endsWith('3')) {
task3[key] = value;
}
if (key.endsWith('4')) {
task4[key] = value;
}
}
By matching the trailing digit, you can take that to put it into the appropriate object.
I'm assuming decription3 decription4 is a typo.
const tasks = {
title1: "Quiet Time",
title2: "Study",
title3: "Go Jogging",
title4: "Eat Breakfast",
description1: "",
description2: "",
description3: "This is going to help to reach my goals and my life to the fullest",
description4: "",
date1: "05/02/2020",
date2: "01/02/2020",
date3: "tomorrow",
date4: "today",
time1: "08:12",
time2: "13:15",
time3: "12:36",
time4: "13:25",
completed1: false,
completed2: true,
completed3: false,
completed4: true,
priority1: "red",
priority2: "yellow",
priority3: "black",
priority4: "white",
tags1: ["Personal", "Work", "School"],
tags2: ["Personal", "School", "Diary Entry"],
tags3: ["Content Creation", "Personal"],
tags4: ["Personal"]
};
const tasksSorted = {};
for (const [key, value] of Object.entries(tasks)) {
const num = key.match(/\d+$/)[0];
tasksSorted[num] ?? = {};
tasksSorted[num][key] = value;
}
console.log(tasksSorted);