How to get all keynames within localStorage

Asked

Viewed 328 times

3

How to catch all the keyNames (not the values) within localStorage and add as option in one element select?

Code in operation here

Explaining the code:

1. The function salvar() saves a key with the given name on input.
2. The function carregar() takes the given keyName and sends as option into the element select
3. The function limpar() clears localStorage completely

But my code only does this with a predetermined key, as I do to take all the keyNames and put them as option?

var te = document.getElementById('te')
function salvar(){  
      localStorage.setItem(te.value, 'Qualquer coisa');
}
function carregar(){
      document.getElementById("op").innerHTML = "<option value='"+ localStorage.key(te.value) +"'>" +localStorage.key(te.value)+ "</option>";
}
function limpar(){
   if (confirm('Você tem certeza que deseja o localStorage?')) {
      localStorage.clear();
   } else {
    // Não faz nada!
   }
}
<input id="te" placeholder="Digite um nome para a Key" />
<div class="salvar">
<button onclick="salvar()">Salvar</button>
<button onclick="carregar()">Carregar</button>
<button onclick="limpar()">Limpar</button>
</div>
<select id="op" name="lsKeys">
</select>

1 answer

6


You can use the Object.keys for this. It returns a array with all the keys of the object.

You can wear something like that:

const keys = Object.keys(localStorage);
console.log(keys);

To create the <option>s, you can create a loop for:

// Mude o seletor abaixo conforme precisar:
const list = document.querySelector('ul');

const keys = Object.keys(localStorage);

for (const key of keys) {
  const option = document.createElement('option');
  option.textContent = key;
  option.value = key;

  list.appendChild(option);
}
  • worked perfectly with some vlw amendments ;)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.