【问题标题】:Get and set object values in localStorage array获取和设置 localStorage 数组中的对象值
【发布时间】:2016-04-05 01:50:29
【问题描述】:

我正在尝试将对象设置为 localStorage,其格式类似于以下:

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

我可以根据从 REST 调用中获得的动态值设置 12。到目前为止我所拥有的是:

// 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));
}

我可以使用这种格式将数据放入 localStorage,但StorageObject[thisItemsListID] 总是进入 if 语句并在 localStorage 中生成重复项,我不确定如何使用变量访问它。如果新 ID 不存在,我会尝试附加它,所以如果 {1:{} 存在但当前 ID 为 2,我需要推送新值。

我在这里很近,也许我需要重新评估我存储数据字符串的格式,但我在这里绕圈子,可以使用正确方向的点。

【问题讨论】:

    标签: javascript arrays local-storage


    【解决方案1】:

    嗯,重复项发生在StorageObject.push(itemProperties)

    试试这个来更新对象:

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

    [编辑]

    如果你想保留[{"1":{"property1":false,"property2":false}},{"2":{"property1":false,"property2":false}}]。有条件的会有点不同。

    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));
    }
    

    【讨论】:

    • 对 - 我想我的帖子并不清楚。我一次只查看一个项目,如果 ID 不存在,则需要附加新项目。因此,如果我已经有 {1:{} 并且当前 ID 是 {2:{} 我需要将它添加到字符串中,这就是我尝试推送新值的原因。
    • 哦,我明白了。好吧,您以错误的方式使用列表。考虑对象[{"1":{"property1":false,"property2":false}},{"2":{"property1":false,"property2":false}}],如果thisItemsListID2!StorageObject[thisItemsListID] 将是错误的。因为数组StorageObject2索引是null
    • @Aaron 我已经更新了答案,条件评估数组内的对象键。
    • 谢谢 Filipe - 我做的事情有点不同,但这为我指明了正确的方向。
    【解决方案2】:

    您是要更新对象还是只是覆盖它? Filipes 响应说明了如何仅通过使用新值重新分配对象来更新整个存储对象。

    如果您想更新对象的部分/值,您可以使用 for 循环来完成。这将允许您扫描数组找到一个属性,然后将其删除、更新、覆盖等。

    这是一个循环的例子。请记住,这是我正在构建的报告库中的一个 sn-p。它使用 angular $scope 但它是一种复杂的类型,与您的更新执行类似的操作(这里我将标签设置为收藏夹/书签)

     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;
                    }
                }
            }
        };
    

    如果您使用像 lowDash 这样的另一个框架,它有一些非常好的帮助函数来更新和评估数组。

    【讨论】:

      猜你喜欢
      • 2014-03-15
      • 1970-01-01
      • 1970-01-01
      • 2021-10-25
      • 1970-01-01
      • 2018-10-25
      • 1970-01-01
      • 2017-04-09
      • 2022-01-17
      相关资源
      最近更新 更多