Find list of Json objects from the localStorage by the name of their keys

4

I know that the localStorage of browsers stores data in key-value format, and that I can retrieve Json objects saved there through the key. Now what I need to do is recover 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 a number to it.

For example: Depósito01 {...              Deposit02 {... Once I retrieved all the records, I would extract these two final characters to find out which last deposit was entered, and +1 the next deposit key name ...

I also do not know how to do this, but I'll try. What I first need is to retrieve objects by the name of their keys ...

    
asked by anonymous 29.04.2018 / 16:43

1 answer

4

You can 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, but if your application has other data saved in localStorage there may be an error, so you have to create an array with only the deposit keys, and you should always update it when there is a change in the localStorage for other actions not to be impaired:

var deposito = [];

for(let element of Object.keys(localStorage)) {
    if(element.search('Deposito') == 0) {
        deposito.push(element);
    }
}
    
29.04.2018 / 17:01