0

I'm trying to set objects into localStorage with a format similar to the following:

[{"1":{"property1":false,"property2":false}},{"2":{"property1":false,"property2":false}}]

Where I'd be able to set the 1 or 2 based on a dynamic value I'm getting from a REST call. What I have so far is:

// check if session exists and create if not
var StorageObject = JSON.parse(localStorage.getItem("session")) || [];

//see if the current id from the REST call is in storage and push with properties if not
if (  !StorageObject[thisItemsListID] ) {
     var itemProperties = {};
     itemProperties[thisItemsListID] = {};
     itemProperties[thisItemsListID]["property1"] = false;
     itemProperties[thisItemsListID]["property2"] = false;

     StorageObject.push(itemProperties);
     localStorage.setItem('session', JSON.stringify(StorageObject));
}

I can get the data into localStorage using this format but StorageObject[thisItemsListID] always gets into the if statement and generates a duplicate item in localStorage and I'm not sure how to access this with a variable. I'm trying to append the new ID if it doesn't exist so if {1:{} exists but current ID is 2 I need to push the new value.

I'm close here and maybe I need to reevaluate the format I'm storing the data string but I'm going in circles here and could use a point in the right direction.

2 Answers 2

1

Well, the duplicate item is happening in StorageObject.push(itemProperties).

Try this to update the object:

//StorageObject.push(itemProperties); <-- remove
StorageObject[thisItemsListID] = itemProperties;

[EDIT]

If you want to keep [{"1":{"property1":false,"property2":false}},{"2":{"property1":false,"property2":false}}]. To conditional would be a bit different.

var haveItem = StorageObject.filter(function(item){
    return Objects.keys(item)[0] == thisItemsListID;
}).length > 0;


if (  !haveItem ) {
     var itemProperties = {};
     itemProperties[thisItemsListID] = {};
     itemProperties[thisItemsListID]["property1"] = false;
     itemProperties[thisItemsListID]["property2"] = false;

     StorageObject.push(itemProperties);
     localStorage.setItem('session', JSON.stringify(StorageObject));
}
Sign up to request clarification or add additional context in comments.

4 Comments

Right - I guess it wasn't clear from my post. I'm only looking at one item at a time and need to append the new item if the ID doesn't exist. So if I have {1:{} already and the current ID is {2:{} I need it added to the string which is why I was trying to push a new value.
Oohn, I see. Well, you're using lists in the wrong way. Considering the object [{"1":{"property1":false,"property2":false}},{"2":{"property1":false,"property2":false}}], if thisItemsListID is 2. !StorageObject[thisItemsListID] would be false. Because the 2 index of the array StorageObject is null.
@Aaron I've updated the answer, the conditional evaluating the object key inside the array.
Thank you Filipe - I did things just a little different but this pointed me in the right direction.
0

Are you trying to update the object or just overwrite it? Filipes response illustrates how to update the entire storage object by just reassigning the object with the new value.

If you wanted to update just as section/ value of the object you could do so using a for loop. This would allow you to scan the array locate the one property and then remove it, updated it, overwrite it etc.

Here is an example of the loop. Bear in mind This is a snippet from a report library I was building. It uses angular $scope but it is a complex type doing a similar action to your update (here I am setting a label as a favorite/bookmark)

 function OnFavoriteComplete(response) {
        var id = response.config.data.reportId; //dynamic values set by client
        var isFavorite = response.config.data.isFavorite;//dynamic values set by client 

        var arrayCount = $scope.reportList.length;
//loop my current collection and look for the property id of the label
//then check to see if true or false/this was a toggle enable disable
        if (isFavorite) {
            for (var i = 0, iLen = arrayCount; i < iLen; i++) {
                if ($scope.reportList[i].reportId == id) {
                    $scope.reportList[i].isFavorite = false;
                }
            }
        }
//if false update the property with the new value
        else {
            for (var i = 0, iLen = arrayCount; i < iLen; i++) {
                if ($scope.reportList[i].reportId == id) {
                    $scope.reportList[i].isFavorite = true;
                }
            }
        }
    };

If you are using another framework like lowDash it has some really nice helper functions for updating and evaluating arrays.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.