frenchie
frenchie

Reputation: 51927

javascript looping through local storage to find an element

I'm making extensive use of local storage and that's great because it helps maintain state by storing the session on the client. The problem however is when updating the session.

I have several lists of objects that I serialize in json and that I put in the session. The objects have several properties, including an ID and a date. At another point, I need to loop through these lists to find out if one of the lists contains one of the objects I'm looking for by ID.

The key I use to store my json includes a date; like this:

var TheData = JSON.stringify(TheListOfMyObjects);
var SessionKey = 'TheListOfObjectsFor' + TheMonth + "." + TheDay + "." + TheYear;
localStorage.setItem(SessionKey, TheData);

Now I need to check if in the session there's an object with a certain ID. I don't know the date property of the object, just its ID. I also don't know which dates have a value in the session or not.

How could I find my object by ID? It'd be nice if I could load the session in memory so that I could loop through it.

Upvotes: 1

Views: 5304

Answers (1)

Jeffrey Sweeney
Jeffrey Sweeney

Reputation: 6114

If the ID is within the object, you would need to extract each localStorage object, and compare the fields.

var obj1 = {ID  : "a",  field: 543}
var obj2 = {ID  : "b",  field: 161}
var obj3 = {ID  : "c",  field: 425}


localStorage.setItem("item1", JSON.stringify(obj1));
localStorage.setItem("item2", JSON.stringify(obj2));
localStorage.setItem("item3", JSON.stringify(obj3));


var ID_Needed = "b";

for(var i = 0; i < localStorage.length; i++) {

    var obj = JSON.parse(localStorage.getItem(localStorage.key(i)));

    if(obj.ID == ID_Needed) {
        console.log(obj);
        break;
    }
}

Upvotes: 3

Related Questions