Get and set object values in localStorage array

时间:2016-04-04 17:19:13

标签: javascript arrays local-storage

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 个答案:

答案 0 :(得分: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));
}

答案 1 :(得分: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.