javascriptlocal-storage

Check if a value from localStorage startsWith a string and console.log() value name


I have a question that's maybe hard to explain... But I'll try my best to. So, I have in localStorage like 3 value and I can't know their name. Let's say there's a, b and c. A value is equal to "Good morning", B value to "Good afternoon", and C value to "Bad night". I want to console.log() if A value, B value or C value startsWith() "Good". And so I don't really know how to do it... Anyone can help me? Thanks. Demo.


Solution

  • You can iterate over the localStorage and check their values:

    for (var i = 0, i < localStorage.length; i++) {
       var value = localStorage.getItem(localStorage.key(i));
       if (value && value.startsWith('Good') console.log('found it!', key, value);
    }
    

    or more simply:

    var valuesWithGood = Object.keys(localStorage).filter(x =>
      localStorage.getItem(x).startsWith("Good")
    );