javascriptarrayslocal-storagesession-storagesessionstorage

I have create an sessionStorage array and have assigned values as shown here. labe


I have created a sessionStorage array named labe and assigned some values as shown below. labe[25,36,42] My key value is labe and I want to change the value from 36 to 87 in sessionStorage itself. How can I do that the same in javascript?


Solution

  • sessionStorage only saves data in string, so when you write something like sessionStorage.setItem('labe', [25,36,42]), [26, 36, 42] will be converted to string '25,36,42' before stored in sessionStorage. That means, you just cannot save an object directly to sessionStorage, or localStorage.

    Usually, we do it like this:

    sessionStorage.setItem('labe', JSON.stringify([25,36,42]))

    and get it back:

    var labe = JSON.parse(sessionStorage.getItem('labe')).

    Then labe become an array again, so you just change labe[1] from 36 to 38, and save it again:

    sessionStorage.setItem('labe', JSON.stringify(labe)).

    That's it.