JSON.stringify后对象存入localStorage时Attributes字段丢失问题
解决localStorage存入对象后Attributes字段为空的问题
问题描述
将对象存入localStorage时,Attributes字段总是为空,但控制台打印该对象时能看到完整数据。相关代码如下:
const ProductAttribute = { productID: productID, Attributes: { [this.name]: productAttrState || this.activeItemIndex }, }; console.log(ProductAttribute); localStorage.setItem( this.localStorageName, JSON.stringify(ProductAttribute) );
核心原因
- JSON序列化特性:如果对象的键为
undefined,JSON.stringify会自动忽略该键值对,直接导致Attributes变成空对象。 - 控制台延迟求值:浏览器控制台打印的对象是引用类型,展开时会读取对象的最新状态。如果
this.name在console.log之后才被赋值,展开时会显示有内容的对象,但JSON.stringify是在this.name为undefined时执行的,因此序列化结果为空。
解决方案
1. 排查this.name的实时值
在代码中添加日志,确认this.name在创建对象和序列化时的实际值:
// 打印this.name的实时值,排查是否为undefined console.log('序列化时的this.name:', this.name); const ProductAttribute = { productID: productID, Attributes: { [this.name]: productAttrState || this.activeItemIndex }, }; console.log(ProductAttribute); localStorage.setItem(this.localStorageName, JSON.stringify(ProductAttribute));
2. 确保this.name提前赋值
检查this.name的赋值逻辑,保证在创建ProductAttribute对象之前,this.name已经被正确设置为非undefined的值。
3. 给计算属性设置默认键
如果无法保证this.name始终有值,可设置默认键避免序列化时丢失数据:
const ProductAttribute = { productID: productID, Attributes: { // 当this.name为undefined时,使用默认键名 [this.name || 'default_attribute']: productAttrState || this.activeItemIndex }, }; localStorage.setItem(this.localStorageName, JSON.stringify(ProductAttribute));
内容的提问来源于stack exchange,提问作者Asifur Rahman
相关产品推荐
相关产品推荐

