Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

213
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda