Search code examples
javascriptecmascript-6destructuring

How do I destructure an object into new objects in a function using es6


Here is the code:

const toDoList = {
    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"]
  };

What I've done: const { title1, description1, date1, time1, completed1, priority1, tags1 } = toDoList;

I haven't been able to figure out how to get passed this point and I'm unsure if the above line would even be used in the function. Much appreciated! EDIT: The challenge I'm trying to solve which is the reason for this post: It is your challenge to destructure the data which is in the form of a single object, then restructure the data into several individual objects each representing a single task datum. This must all be done programmatically. As an additional challenge, think about how you can use arguments to configure the behaviour of your function such that you can represent 1 or 100 (or any amount of) users without having to rewrite any of the function definition. EDIT2: I believe my end result is supposed to be 4 objects, each with their own title, description, date etc. Similar to how this would work: const { title1, description1, date1, time1, completed1, priority1, tags1 } = toDoList; however that won't be dry coding as I would have to have it so that I am able to run through the code even if there are like 100 titles each needing it's own object.


Solution

  • I don't think it will serve you to offer a complete solution, but here is an example of one way of extracting a task from the toDoList

    const task1 = {};
    for (const [key, value] of Object.entries(toDoList)) {
      if (key.endsWith('1')) {
        task1[key] = Array.isArray(value) ? [...value] : value;
      }
    }
    
    console.dir(task1);
    
    /*
    { 
      completed1: false
      date1: "05/02/2020"
    ​  description1: ""
    ​  priority1: "red"
    ​  tags1: [ "Personal", "Work", "School" ]
    ​  time1: "08:12"
    ​  title1: "Quiet Time"
    }
    */