如何使用Javascript更改本地存储中项目的值 [英] How to change the value of an item in localstorage using Javascript

查看:81
本文介绍了如何使用Javascript更改本地存储中项目的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在localStorage中存储了一个对象.

I have an object stored in localStorage.

let ship = {
    name: "black pearl",
    captain: "Jack Sparraw"
  };

 localStorage.setItem("ship", JSON.stringify(ship));

现在,我想将名称"更改为新名称.如何使用Javascript实现?

Now I want to change "name" to a new name. How to achieve it using Javascript?

(下面的代码不起作用,但是它给出了我想要做什么的想法)

(The following code does not work, but it gives an idea what I want to do)

 localStorage.setItem(localStorage.getItem("ship").name, "newName");

推荐答案

您检索JSON,进行解析,更新从解析中获得的对象,对结果进行字符串化并存储该结果:

You retrieve the JSON, parse it, update the object you get from parsing it, stringify the result, and store that result:

const ship = JSON.parse(localStorage.getItem("ship"));
ship.name = "newName";
localStorage.setItem("ship", JSON.stringify(ship));

如果您想一站式完成所有工作(尽管我不建议这样做,则更难以阅读,维护和调试;将缩小部分留给缩小部分):

If you want to do it all in one line (although I don't recommend it, it's harder to read, maintain, and debug that way; leave minification to minifiers):

localStorage.setItem("ship", JSON.stringify(Object.assign(JSON.parse(localStorage.getItem("ship")), {name: "newName"})));

这篇关于如何使用Javascript更改本地存储中项目的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆