Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

205
Views
Retrieve array of objects from local storage

Trying to make to-do list but I have difficulties with local storage. First i don't understand why does local storage returns [object Object] instead of actual text. Secondly at some point local storage becomes empty and then begins to fill in from the beginning. That's so confusing for me

function addTask() {
    let addTaskButton = document.getElementById('add-task-button')
    let list = document.getElementById('task-list');
    let li = document.createElement('li');
    let checkbox = document.createElement('input');
    let taskText = document.createElement('span');
    let delButton = document.createElement('button');
    let btnText = document.createTextNode('Delete task');

    checkbox.type = 'checkbox';
    checkbox.className = 'checkbox';
    taskText.innerText =  document.getElementById('input-task').value;
    taskText.className = 'task';
    delButton.className = 'delete-btn';
    delButton.addEventListener('click', deleteTask)
    delButton.addEventListener('click', updateStorage)
    addTaskButton.addEventListener('click', updateStorage);

    delButton.appendChild(btnText);
    li.appendChild(checkbox);
    li.appendChild(taskText);
    li.appendChild(delButton);
    list.appendChild(li);

    document.getElementById('input-task').value = '';


    taskList.push({
        text: taskText.innerText,
        checked: false
    });
}

let taskList = [];

function updateStorage() {
    localStorage.setItem('tasks', JSON.stringify(taskList));
    console.log(taskList)
}

function deleteTask () {
    this.parentNode.remove();
}

document.getElementById('add-task-button').addEventListener('click', addTask);

function loadList() {
    document.querySelector('ul').innerHTML = JSON.parse(localStorage.getItem('tasks')) || [];
}

window.addEventListener('load', loadList);
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

this way:

const 
  inputTask = document.querySelector('#input-task')
, addTaskBt = document.querySelector('#add-task-button')
, taskList  = document.querySelector('#task-list')
, tasks     = JSON.parse(localStorage.getItem('tasks') || '[]')
, savTasks  =_=> localStorage.setItem('tasks',JSON.stringify(tasks))
  ;
tasks.forEach( newLItask )

addTaskBt.onclick =_=>
  {
  if (inputTask.value.trim()==='') return
  
  let taskElm = { txt: inputTask.value.trim(), checking:false }
  tasks.push( taskElm )

  newLItask( taskElm )
  savTasks()
 
  inputTask.value = ''
  inputTask.focus()
  }
taskList.onclick = ({target}) => // event delegayion for all buttons & checkboxes
  {
  if (!target.matches('button.delete-btn, input[type=checkbox]')) return

  let taskIndex = tasks.findIndex(task => task===target.closest('li').ref )

  if (target.matches('input[type=checkbox]'))
    tasks[taskIndex].checking = target.checked
  else  // delete
    {
    tasks.splice(taskIndex,1)
    target.closest('li').remove()
    }
  savTasks()
  }
function newLItask( taskElm )
  {
  taskList
  .appendChild(Object.assign(document.createElement('li'), {ref:taskElm} ))
  .innerHTML = `
    <input type="checkbox" class="checkbox" ${taskElm.checking ? 'checked': ''}>
    <span class="task"> ${taskElm.txt} </span>
    <button class="delete-btn">Delete task</button>`
  } 

for testing:

#task-list {
  padding         : 0;
  list-style-type : none;
  }
#task-list li {
  margin     : .4em 0;
  }
#task-list li > span {
  display       : inline-block;
  width         : 20em;
  border-bottom : 1px solid lightsteelblue;
  margin        : 0 .6em 0 0;
  }
#task-list input[type=checkbox]:checked + span {
  text-decoration       : line-through ;
  text-decoration-style : wavy;
  text-decoration-color : orangered;
  }
<input type="text" id="input-task" placeholder="input task" size="26">
<button id="add-task-button" >add task</button>
<ul id="task-list"></ul> 
about 4 years ago · Juan Pablo Isaza Report

0

I made this a comment on the original post, but I think this might qualify as the answer...

The JSON.Parse gets you an object, and when you try to use that object as a string (setting the innerHTML of an element), you'll get the "[object Object]" text. What's stored in localStorage is a string already that represents your JSON. Just set the innerHTML to what comes back from your localStorage.getItem('tasks') call.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!