Get the value of localstorage

Hi thanks for you help, i have tryied with your code but i get problems with the syntax (even if i think that it’s good way). Regarding this one, this is not working, result gives always same value 2 and 4 as true even witch boxes are checked.

Actually i am here :
with this code :

for (const [key, value] of Object.entries(localStorage)) {
  console.log("TEST3",`${key}: ${value}`);
}

and i get the result in console.log:
TEST3 checkboxValues: {“checkbox1”:false,“checkbox2”:true,“checkbox3”:true,“checkbox4”:false,“checkbox5”:true,“checkbox6”:true,“checkbox7”:false,“checkbox8”:true,“checkbox9”:false}
but when i try this :

for (const [key, value] of Object.entries(localStorage)) {
    if(value=='true') console.log(`${key}: ${value}`);
  }

I get nothing, i don’t understand why the if(value==‘true’) is not working

My CodePen always gives values 2 and 4 as true regardless of which boxes are ticked (checked) because it is saving to localStorage the initial checkbox values. The initial values are defined within the HTML code. There is no code there to update localStorage everytime a checkbox is changed. That code could be added.

I am not clear why you are using JSON when localStorage already provides key:value pairs. However, I appreciate that you may be using JSON so as to keep checkbox values together as a group.

1 Like

:sweat_smile: Ok understand sorry for my mistake.
Anyway i get the solution finally :

const STORAGE_KEY_NAME = 'checkboxValues';
const storageBoxes=JSON.parse(window.localStorage.getItem(STORAGE_KEY_NAME)) ?? {}
for (const [key, value] of Object.entries(storageBoxes)) {
if (value === true) {
    console.log(`Case "${key}" cochée !`)
  }}

Ok i found also how to use the backticks !!!

I don’t understand what is the two ?? {} but now it’s working.
Thanks a lot the help of everyone on this forum.

It’s the nullish coalescing operator.

You could also write it like this for a little more clarity:

const json = JSON.parse(window.localStorage.getItem(STORAGE_KEY_NAME));
const storageBoxes = json ?? {};

What the ?? operator does is evaluate the operand on its left side, namely the json variable. As long as the json variable is not null or undefined, it will return the value held in the json variable. Otherwise it will return the value of its right hand operand, namely an empty object {}.

This is a standard way to assign a default value to a variable that might not have been initialized.

HI Mr Hibbard, thanks a lot for you answer and your last post from 2016 witch bring me to all this troubles ;).
But now i am going forward even if i find very difficult this language…Greetings from France.

1 Like

No worries. Glad you found it useful :slight_smile:

1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.