Home > Mobile >  How do i store an array in localstorage and then get the contents and then add them to a select obje
How do i store an array in localstorage and then get the contents and then add them to a select obje

Time:04-19

This is the code i am using to get the array and then add them to the select object.

var select = document.getElementById('select');
var theArray = localStorage.getItem("array")
JSON.parse(theArray)
if (theArray != null){
  for (var i=0; i > theArray.length; i  ){
    select.add(theArray[i])
  }
}

Here is the code i am using to set the localStorage values.

var select = document.getElementById('select');
var option = document.createElement("option");
      option.text = visText;
      option.value = actVal;
      select.add(option)
      theArray[theArray.length 1] = option;
localStorage.setItem("array",JSON.stringify(theArray))

Can anybody tell me how to fix this?

CodePudding user response:

Looks like you forgot to assign the parsed Json to a variable:

let select = document.getElementById('select')
let data = JSON.parse(localStorage.getItem('array'))

for(let entry of data) {
  select.add(new Option(entry))
}

Not 100% sure if it works but should do.

CodePudding user response:

You can just call the session and local storage with dot notation. The snippet below shows this. However, the snippets here are sandboxed, and cannot be written to. So, to demonstrate how to populate a select element from an array, I used a try..catch block so when it errored out, it would at least populate the select options with the original array variable.

const array = new Array(10).fill(0).map((elm, idx) => (elm = idx, elm));
let arrayFromStorage;

try {
  window.localStorage.myArray = JSON.stringify(array);
  arrayFromStorage = JSON.parse(window.localStorage.myArray);
} catch (error) {
  console.warn(error.message)
  arrayFromStorage = array;
}

arrayFromStorage.forEach(elm => {
  const opt = document.createElement('option');
  opt.value = elm;
  opt.innerText = `option ${elm}`;
  document.querySelector('select').append(opt);
})
<select></select>

If you copy/paste this into a browser console, you can see that it can be set and called using dot notation

const array = new Array(10).fill(0).map((elm, idx) => (elm = idx, elm));
let arrayFromStorage;
window.localStorage.myArray = JSON.stringify(array);
arrayFromStorage = JSON.parse(window.localStorage.myArray);
  • Related