You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用JavaScript修改localStorage中对象的属性值

How to Update a Property of an Object Stored in localStorage

Got it, let's walk through exactly how to modify the name property of your ship object in localStorage. The key thing to remember here is that localStorage only stores string values—so we have to convert between JSON strings and JavaScript objects to make changes.

Here's the step-by-step breakdown:

  1. Pull the stored data from localStorage using the key "ship"
  2. Convert the JSON string back to a JavaScript object (since we stored it with JSON.stringify() earlier)
  3. Update the name property on the object
  4. Turn the updated object back into a JSON string
  5. Save the new string back to localStorage using the same key

Working Code Example

// 1. Get the stored JSON string
const storedShip = localStorage.getItem("ship");

// Add a check to avoid errors if the key doesn't exist
if (storedShip) {
  // 2. Parse the string into a usable object
  let ship = JSON.parse(storedShip);
  
  // 3. Update the name property to your new value
  ship.name = "The New Black Pearl"; // Replace with your desired name
  
  // 4. Convert back to JSON string & 5. Save it back to localStorage
  localStorage.setItem("ship", JSON.stringify(ship));
}

Why Your Original Attempt Didn't Work

Your line localStorage.setItem(localStorage.getItem("ship").name, "newName"); has two main issues:

  • localStorage.getItem("ship") returns a string, not an object—so you can't directly access .name on it. You need to parse it first to get the object.
  • The first argument to setItem() should be the key name ("ship"), not the value of the name property. Your code was trying to create a new localStorage entry with the old ship name as the key, which isn't what you want.

Adding the if (storedShip) check is a good habit—it prevents JSON.parse() from throwing an error if the "ship" key doesn't exist in localStorage yet.

内容的提问来源于stack exchange,提问作者Ning

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 07:58:57