Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading