为待办事项列表添加任务

时间:2020-03-12 11:40:49

标签: javascript

我正在尝试为每个具有特定标题的待办事项列表添加任务。

我可以通过ID获得特定的待办事项列表并向其中添加一些任务吗? 我是Java语言的新手,所以我在Google上搜索了有关为没有结果的特定列表添加列表的信息:(

class Model {
  constructor() {}

  this.todos = [
      { 
        id: 1,
       title: 'Outside',
       text: 'Running',
       complete: false,
       tasks: [
       { id: 1, text: 'Run a marathon', complete: false},
       { id: 2, text: 'Run with freinds', complete: false}
       ]
    },
    { 
        id: 2,
       title: 'Garden',
       text: 'Plant',
       complete: false,
       tasks: [
       { id: 1, text: 'Plant a garden', complete: false},
       { id: 2, text: 'Water the garden', complete: false}
       ]
    }];

    addTodo(todoText) {
        const todo = {
        id: this.todos.length > 0 ? this.todos[this.todos.length - 1].id + 1 : 1,
        text: todoText,
        complete: false,
        tasks: []
    }

    this.todos.push(todo)
  }
  }

像addTodo函数那样为特定的待办事项列表添加任务真的是真的吗?

addTodoTask(todoTaskText) {
        const todoTask = {
        id: this.todos.tasks.length > 0 ? this.todos[this.todos.tasks.length - 1].id + 1 : 1,
        text: todoText,
        complete: false,
    }

    this.todos.tasks.push(todoTask)
  }

以及如何在javascript中添加列表的列表,如:

<ul>
<li>Running
<ul>
<li>Run a marathon</li>
<li>Run with freind</li>
</ul>
</li>
</ul>

1 个答案:

答案 0 :(得分:1)

我举了一个例子,说明如何使用字典而不是数组以及随机ID。我认为您会发现它更干净,更简单:

class Model {
  constructor() { }

  todos = {
    1: {
      id: 1,
      title: 'Outside',
      text: 'Running',
      complete: false,
      tasks: {
        1: { id: 1, text: 'Run a marathon', complete: false },
        2: { id: 2, text: 'Run with freinds', complete: false }
      }
    },
    2: {
      id: 2,
      title: 'Garden',
      text: 'Plant',
      complete: false,
      tasks: {
        1: { id: 1, text: 'Plant a garden', complete: false },
        2: { id: 2, text: 'Water the garden', complete: false }
      }


    }
  }


  getRandomId = () => {
    return '_' + Math.random().toString(36).substr(2, 9);
  }

  addTodo(todoText) {
    const id = this.getRandomId();
    const todo = {
      id,
      text: todoText,
      complete: false,
      tasks:{}
    }

    this.todos[id] = todo;
  }

  addTodoTask(todoTaskText,todoId) {//Pass also the id of the todo, to know where this task belongs to.
    const id = this.getRandomId();
    const todoTask = {
      id,
      text: todoTaskText,
      complete: false,
    }

    this.todos[todoId].tasks[id] = todoTask
  }
}

通过这种方式,您可以仅通过ID轻松编辑/删除待办事项和任务,而无需使用任何凌乱的Array.filter等