Home > Enterprise >  Returns key and value of a localstorage object
Returns key and value of a localstorage object

Time:03-09

I get a localstorage built like this:

  TYPE_MAPPING  : {"type":{"B2B":"B2B","UNKNOWN":"B2C","blabla":"B2C"}}

when I want to retrieve the key and value from localstorage

  const type = localStorage.getItem(TYPE_MAPPING);

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

I get the following error message :

  TS2769: No overload matches this call.   
  Overload 1 of 2, '(o: { [s: string]: string; } | ArrayLike<string>): [string, string][]', gave the following error.     
  Argument of type 'string | null' is not assignable to parameter of type '{ [s: string]: string; } | ArrayLike<string>'.       
  Type 'null' is not assignable to type '{ [s: string]: string; } | ArrayLike<string>'.   Overload 2 of 2, '(o: {}): [string, any][]', gave the following error.     
  Argument of type 'string | null' is not assignable to parameter of type '{}'.       Type 'null' is not assignable to type '{}'.

what would be the solution to recover the keys and values of the localStorage ?

CodePudding user response:

**localstorage.getItem** return a string, so you have to parse it before

  const type = JSON.parse(localStorage.getItem(TYPE_MAPPING));

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

CodePudding user response:

The type object you're trying to get is nested in the type variable. Try this:

const type = localStorage.getItem(TYPE_MAPPING);

  for (const [key, value] of Object.entries(type.type)) {
  console.log(`${key}: ${value}`);
}
  • Related