Search localStorage Json object list for your key name

Asked

Viewed 153 times

4

I know that the browser localStorage stores data in the key-value format, and that I can recover the Json objects saved there through the key. Now what I need to do is retrieve all the records whose key starts with "Deposit". This is because I want to create a sequence generator, so that each deposit object key has added to it a number.

For example: Deposition01 {... Deposition02 {... Once recovered all the records, I would extract these two final characters to find out which deposit was last inserted, and increment by +1 in the name of the next deposit key...

Also do not know how to do this, but I will try. What I need first is to recover the objects by the name of your keys...

1 answer

4


You can make a loop:

localStorage.clear();

localStorage.Deposito1 = 'item 1';
localStorage.Deposito2 = 'item 2';
localStorage.Deposito3 = 'item 3';

for(let i = 0; i < localStorage.length;) {
    console.log(localStorage[`Deposito${i++}`]);
}

To get the last number just use:

localStorage[`Deposito${localStorage.length + 1}`] = 'item n';

This is a simple way however, if in your application you have other data saved in localStorage there may be some error, for this to be created an array only with the deposit keys, and should always update it when there is a change in localStorage for other actions not to be harmed:

var deposito = [];

for(let element of Object.keys(localStorage)) {
    if(element.search('Deposito') == 0) {
        deposito.push(element);
    }
}
  • Yeah, I didn’t think I wouldn’t need a loop, I figured I’d have some method to generate it. Another thing I don’t know: the symbol that represents "any character that comes after" in javascript, which in this case is the "$" then... Thanks, it helped a lot.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.