javascript-Localstorage:使用Stringify更改特定数组的值
作者:互联网
我不知道问题是否非常准确,但是我正在尝试从localstorage数组更改值.
这是我的本地存储的样子:
[{"id":"item-1","href":"google.com","icon":"google.com"},
{"id":"item-2","href":"youtube.com","icon":"youtube.com"},
{"id":"item-3","href":"google.com","icon":"google.com"},
{"id":"item-4","href":"google.com","icon":"google.com"},
{"id":"item-5","href":"youtube.com","icon":"youtube.com"},
{"id":"item-6","href":"asos.com","icon":"asos.com"},
{"id":"item-7","href":"google.com","icon":"google.com"},
{"id":"item-8","href":"mcdonalds.com","icon":"mcdonalds.com"}]
关键是“结果”.
如何为id:item-6,href:设置项目.例如.项目6,href是asos.com.如何将更改设置为stackoverflow.com?
我认为这将是这样的:
localStorage.setItem("result", JSON.stringify( ??? ));
编辑:
我已经实现了从本地存储中检索数据:
这是工作的小提琴:http://jsfiddle.net/kZN4y/.使用相同的编码,我想更新update click中提到的值.那可能吗?
谢谢
解决方法:
就个人而言,我会毫不犹豫地创建处理整个对象的函数,在您的情况下,例如:
var blob = [{"id":"item-1","href":"google.com","icon":"google.com"},
{"id":"item-2","href":"youtube.com","icon":"youtube.com"},
{"id":"item-3","href":"google.com","icon":"google.com"},
{"id":"item-4","href":"google.com","icon":"google.com"},
{"id":"item-5","href":"youtube.com","icon":"youtube.com"},
{"id":"item-6","href":"asos.com","icon":"asos.com"},
{"id":"item-7","href":"google.com","icon":"google.com"},
{"id":"item-8","href":"mcdonalds.com","icon":"mcdonalds.com"}];
// define helper functions
Storage.prototype.setBlob = function (blob)
{
for (i in blob) {
// example of storageObjet: {'item-3': {'href': 'google.com', 'icon': 'google.png'}}
var struct={};
for (key in blob[i]) {
if (key != 'id') {
struct[key] = blob[i][key];
}
};
this.setObject(blob[i].id, struct);
}
}
Storage.prototype.setObject = function(key, obj) {
this.setItem( key, JSON.stringify(obj) );
};
Storage.prototype.getObject = function(key) {
return JSON.parse(this.getItem(key));
};
// do stuff
sessionStorage.clear();
sessionStorage.setBlob(blob);
var key = 'item-6';
var item = sessionStorage.getObject(key);
item.href = 'stackoverflow.com';
sessionStorage.setObject(key, item);
for (key in sessionStorage) {
if (typeof(sessionStorage[key]) == 'string') {
var item2 = sessionStorage.getObject(key);
$('#stuff').append( $('<div>').html(item2.href) );
}
}
注意:在此示例中,我使用sessionStorage代替localStorage,但是接口相同,都使用Storage原型.
如您所见,我将每个项目的结构更改为以下形式:{‘item-3’:{‘href’:’google.com’,’icon’:’google.png’}}.我这样做是因为它更好地反映了javascript,localStorage和键/值方式的整体概念,并大大简化了用法.
在此示例中,您有:
var item = sessionStorage.getObject(key);
item.href = 'stackoverflow.com';
sessionStorage.setObject(key, item);
这对我来说似乎是一种非常实用的处理localStorage的方法.
此外,“ setBlob”功能可以处理每个项目随机和可变数量的元素.如果需要,这允许您拥有一个具有5个属性的项目,而其他所有项目具有2个属性.只要有一个用键“ id”调用的元素,它就可以与“扁平”结构一起使用.
编辑:调试,并切换到一个更经典的setValue(key,item);
标签:stringify,local-storage,json,javascript,jquery 来源: https://codeday.me/bug/20191202/2085917.html