Search code examples
javascriptjsonlocal-storage

Create Object with Name & Value of specific localstorage


Found this code on the net:

const keys=Object.keys(localStorage).filter(key=>key.includes('doinclude'));
const todos=keys.map(key=>JSON.parse(localStorage.getItem(key)));

The resulting 'todo' is an object holding the localstorage values.

What to change in the above code to include both name and value of each localStorage entry?


Solution

  • Here is a version that als makes sure it does no fail on content that is not JSON

    But the better way is to save the doincludes in their own array/object

    const todos = Object.keys(localStorage)
      .filter(key => key.includes('doinclude'))
      .map(key => {
        try {
          return {
            name: key,
            value: JSON.parse(localStorage.getItem(key)),
          };
        } catch (e) {
          return {
            name: key,
            value: localStorage.getItem(key), // Return as a string if it's not JSON
          };
        }
      });
    
    console.log(todos);
    

    or returning key:value

    const todos = Object.keys(localStorage)
      .filter(key => key.includes('doinclude'))
      .reduce((acc, key) => {
        try {
          acc[key] = JSON.parse(localStorage.getItem(key));
        } catch (e) {
          acc[key] = localStorage.getItem(key);  // Add raw string if not JSON
        }
        return acc;
      }, {});
    
    console.log(todos);