javascript 修改本地存储?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12412217/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 16:08:03  来源:igfitidea点击:

Modify localstorage?

javascriptlocal-storage

提问by Hyman

I'm using simplecartjs to power an online store. It stores it's data in local storage, which looks like this:

我正在使用 simplecartjs 为在线商店提供动力。它将数据存储在本地存储中,如下所示:

{"SCI-1":{"quantity":1,"id":"SCI-1","price":20,"name":"Mattamusta -teippi","size":"Tyhj?"},"SCI-3":{"quantity":1,"id":"SCI-3","price":19,"name":"Mohawk .vaimennusmatto 48 x 39cm"},"SCI-5":{"quantity":2,"id":"SCI-5","price":8,"name":"Car Speaker -hajuste","color":"Green Tea"},"SCI-7":{"quantity":1,"id":"SCI-7","price":50,"name":"Asennuspaketti"},"SCI-9":{"quantity":1,"id":"SCI-9","price":30,"name":"Quartz-kalvot","color":"Yellow","size":"50cm x 30cm"},"SCI-11":{"quantity":1,"id":"SCI-11","price":30,"name":"Quartz-kalvot","color":"True Blue","size":"50cm x 30cm"}}

And I want to add this line beforeit's closed.

我想它关闭之前添加这一行。

"SCI-12":{"quantity":1,"id":"SCI-12","price":5,"name":"Toimituskulut"}

However, the amount of products will depend on user, and so on SCI-12must grow with the number of items.

但是,产品的数量将取决于用户,因此SCI-12必须随着项目的数量而增长。

EDITActually, it doens't have to use SCI-1, it can be anything, as long as it's after the items.

编辑实际上,它不必使用SCI-1,它可以是任何东西,只要它在项目之后。

EDIT2Here's what I'm trying... But without luck.

EDIT2这就是我正在尝试的......但没有运气。

$("#matkahuolto").click(function(){
    var value_object = '"Toimituskulut":{"quantity":1,"id":"Toimituskulut","price":5,"name":"Toimituskulut"}';
    var json_object = JSON.parse(localStorage.your_json); // convert string to object

    json_object["simpleCart_items"] = value_object; // add value

    localStorage.your_json = JSON.stringify(json_object);  // store it again.

    });

    $("#posti").click(function(){
    var json_object = JSON.parse(localStorage.your_json); // convert string to object

    json_object["simpleCart_items"] = value_object; // add value

    localStorage.your_json = JSON.stringify(json_object);  // store it again.

    });

EDIT3A screenshot of localstorage. LocalStorage

EDIT3 本地存储的屏幕截图。 本地存储

回答by Hyman

The first thing you need to understand is how items are stored in localStorage, which is basically like a hashmap/dictionary in that the items are stored in key value pairs.

您需要了解的第一件事是项目如何存储在localStorage 中,它基本上类似于哈希图/字典,因为项目存储在键值对中。

For example to store a stringlocalStorageyou would do something like

例如存储一个stringlocalStorage你会做类似的事情

localStorage["myKey"] = "some value";

To retrieve the value you would just to the reverse

要检索您只需反向的值

var myValue = localStorage["myKey"];

The next thing to realize is that you can in fact onlystore strings in localStorage, so if you want to store a object you need to first convert it to a string representation. This is usually done by converting the object to JSONwhich is a compact notation used to represent an object as a string. To convert an object to JSON you just use the JSON.stringifymethod, and to parse an item you use the JSON.parsemethod

接下来要意识到的是,您实际上只能在 localStorage 中存储字符串,因此如果您想存储一个对象,您需要先将其转换为字符串表示形式。这通常是通过将对象转换为JSON来完成的,JSON是一种用于将对象表示为字符串的紧凑符号。要将对象转换为 JSON,您只需使用该JSON.stringify方法,并解析您使用该JSON.parse方法的项目

For example to convert an object to JSON

例如将对象转换为 JSON

var someObject = {id: 1, name: 'Test'};

var jsonSomeObject = JSON.stringify(someObject); 
// jsonSomeObject looks like "{"id":1,"name":"test"}"

And to read an object from JSON

并从 JSON 读取对象

someObject = JSON.parse(jsonSomeObject);

So now in your case assuming that your object contains the appropriate data all you need to do is stringifyyour object and add it to localStorageusing some key,

所以现在在你的情况下假设你的对象包含适当的数据你需要做的就是stringify你的对象并localStorage使用一些键将它添加到,

var jsonData = JSON.stringify({"SCI-12":{"quantity":1,"id":"SCI-12","price":5,"name":"Toimituskulut"}});

localStorage["aKey"] = jsonData;

and when you want to access this data later (presumably after coming back to the page)

当你想稍后访问这些数据时(大概是在回到页面之后)

var mySCI = JSON.parse(localStorage["aKey"])

If you are trying to update a specific entry in localStorage then you would just read it in and then overwrite it, for example

例如,如果您尝试更新 localStorage 中的特定条目,那么您只需读取它然后覆盖它

var mySCI = JSON.parse(localStorage["aKey"]);
mySCI.SCI-12.quantity = 2;
localStorage["aKey"] = JSON.stringify(mySCI);

Keep in mind that while most browsers have built in support for JSON some older ones don't, if this is an issue you can include Douglass Crockfords JSON-jsscript to provide support.

请记住,虽然大多数浏览器都内置了对 JSON 的支持,但一些较旧的浏览器没有,如果这是一个问题,您可以包含 Douglass Crockfords JSON-js脚本来提供支持。

Edit:

编辑:

Based on the screenshot you just posted, you can see that the key under which the values are stored in localStorage is in fact simpleCart_items (and not your_json which are using in your code), and that the object that is being stored has a object stored under the key "SCI-1) (and probably others under "SCI's"). So what you would need to do is something like the following

根据您刚刚发布的屏幕截图,您可以看到在 localStorage 中存储值的键实际上是 simpleCart_items(而不是在您的代码中使用的 your_json),并且正在存储的对象存储了一个对象在“SCI-1”键下)(可能还有“SCI”下的其他键)。所以你需要做的是如下

 $("#matkahuolto").click(function(){
    var value_object = {quantity: 1, id: 1, name: "someName"} ; 
    var jsonObject = JSON.parse(localStorage["simpleCart_items"]);
    json_object["SCI_1"] = value_object; // add value

 localStorage["simpleCart_items"] = JSON.stringify(json_object);  // store it again.

});

$("#posti").click(function(){
 // convert string to object
 var json_object = JSON.parse(localStorage["simpleCart_items"]); 

json_object["SCI-1"] = value_object; // add value

 localStorage["simpleCart_items"] = JSON.stringify(json_object);  // store it again.

});

回答by Hyman

LocalStorage stores all data as as string of text. So it would be easiest to modify it before it has been converted to a string of text.

LocalStorage 将所有数据存储为文本字符串。因此,在将其转换为文本字符串之前对其进行修改是最容易的。

Otherwise you need to pull the json string into an object, add the property, convert it back to a string and store it.

否则,您需要将 json 字符串拉入一个对象,添加属性,将其转换回字符串并存储它。

Sample Code

示例代码

var json_object = JSON.parse(localStorage.your_json); // convert string to object
json_object[key] = value_object; // add value
localStorage.your_json = JSON.stringify(json_object);  // store it again.

Note

笔记

This is what indexedDB is for.
One might want to consider this as a substitute.

这就是 indexedDB 的用途。
人们可能想将其视为替代品。

回答by Adrian May

Or you could let http://rhaboo.orgdo the heavy lifting and write:

或者你可以让http://rhaboo.org做繁重的工作并写:

var store = Rhaboo.persistent("My Cart");
if (store.cart === undefined) 
  store.write('cart', []);
//otherwise it must have data in from before

$("#matkahuolto").click(function(){
  store.cart.push ({
      "quantity":1,  "id":"Toimituskulut",
      "price":5,     "name":"Toimituskulut"  });
});

$("#show").click(function(){ console.log( 
    store.cart.map(function (i) {
      return i.quantity + " " + i.id + "s at " + i.price + " each"
    }).join(' plus '); );  
 });

BTW, I wrote rhaboo.

顺便说一句,我写了 rhaboo。