我将此值存储在我的键值
中现在在我的HTML DOM上,我添加了一些数据[你可以使用任何变量给出示例]我想更新下面数组的description:
参数,你能指导我如何简单地更新它的值以任何变量的值为例
key - Section283
值 -
{
"subtitle": "",
"description": "<p>We are glad to hear from you!</p>",
"id": "689",
"title": "footer",
"sectionType": "283",
"latitude": "0",
"longitude": "0",
"tags": "",
"userId": "32",
"internalLink": "menu-lam"
}
答案 0 :(得分:1)
首先,让我们清楚你根本没有阵列。你所展示的是一个对象。在纯JavaScript中,除非名称中包含空格,否则不需要引用键名。使用对象,更新其中一个属性非常简单:
// Note the the property names do not need to be quoted unless they contain spaces:
var myObject = {
subtitle: "",
description: "<p>We are glad to hear from you!</p>",
id: "689",
title: "footer",
sectionType: "283",
latitude: "0",
longitude: "0",
tags: "",
userId: "32",
internalLink: "menu-lam"
}
// Getting property value out of an object:
console.log("Original value of \"description\" property: " + myObject.description);
// Changing property value:
myObject.description = "Something New";
// Getting new value:
console.log("Current value of \"description\" property: " + myObject.description);
&#13;
如果您需要在localStorage
中存储此类内容,则必须将该对象转换为string
(因为这是唯一可以存储的数据类型localStorage
)。您可以使用本机JSON
对象轻松完成此操作,如下所示:
var myObject = {
subtitle: "",
description: "<p>We are glad to hear from you!</p>",
id: "689",
title: "footer",
sectionType: "283",
latitude: "0",
longitude: "0",
tags: "",
userId: "32",
internalLink: "menu-lam"
}
console.log("Original type for \"myObject\": " + typeof myObject);
// Convert object to JSON
var jObj = JSON.stringify(myObject);
// Check converted type:
console.log("Type for \"myObject\": " + typeof jObj);
&#13;
创建JSON字符串后,您可以将其存储在localStorage
中,如下所示:
localStorage.setItem("myData", jObj);
然后,要检索数据,请编写:
var jsonString = localStorage.getItem("myData");
最后,您需要将字符串转换回对象,然后才能正常使用它:
// This sets up what you'd get back from localStorage:
var localStorageString = `{
"subtitle": "",
"description": "<p>We are glad to hear from you!</p>",
"id": "689",
"title": "footer",
"sectionType": "283",
"latitude": "0",
"longitude": "0",
"tags": "",
"userId": "32",
"internalLink": "menu-lam"
}`;
// Convert the string back to an object
var obj = JSON.parse(localStorageString);
// Use the object as normal:
obj.description = "Something New";
console.log(obj.description);
&#13;
答案 1 :(得分:0)
您可以使用类似的设置localStorage
localStorage.setItem(key, 'Section283');
希望这有帮助!
答案 2 :(得分:0)
这就是我的想法。使用您的密钥访问您的值,然后将其转换为Javascript对象并更新它的描述属性。然后将json对象转换回字符串并使用带有Array的键来设置(基本上覆盖)该值。在黑暗中刺伤。
var jsonObj = json.parse(yourArray['Section283']);
jsonObj.description = 'Whatever you want here';
yourArray['Section283'] = JSON.stringify(jsonObj);