【发布时间】:2016-04-05 01:50:29
【问题描述】:
我正在尝试将对象设置为 localStorage,其格式类似于以下:
[{"1":{"property1":false,"property2":false}},{"2":{"property1":false,"property2":false}}]
我可以根据从 REST 调用中获得的动态值设置 1 或 2。到目前为止我所拥有的是:
// 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