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

如何以字符串变量为键在嵌套对象中新增对象并操作Chrome存储

问题解决与代码修正

核心语法错误修复

你写的if (typeof data.presentations.'(presentationtitle)' === 'undefined')是错误语法,JavaScript中用变量作为对象键时,必须使用方括号语法,正确写法是:

if (typeof data.presentations[presentationtitle] === 'undefined')

代码逻辑优化

你的代码还有两个可优化的问题:

  • else分支重复调用chrome.storage.sync.get('presentations')完全没必要,外层已经获取到了data对象,直接复用即可
  • 直接设置新的presentations对象会覆盖原有存储中的其他演示数据,应该合并现有数据后再保存

修正后的完整代码:

let presentationtitle = 'Test presentation 123';

chrome.storage.sync.get(['presentations', 'general'], function(data) {
  // 首次打开弹窗,初始化完整设置
  if (typeof data.presentations === 'undefined') {
    const extensionsettings = {
      presentations: {
        [presentationtitle]: {}
      },
      general: {
        setting1: true,
        setting2: false
      }
    };
    chrome.storage.sync.set(extensionsettings, () => {});
  } else {
    // 检查当前演示标题是否已存在于存储中
    if (typeof data.presentations[presentationtitle] === 'undefined') {
      // 合并现有演示数据,新增当前标题的条目
      const updatedPresentations = {
        ...data.presentations,
        [presentationtitle]: {
          duration: '00:00:00'
        }
      };
      chrome.storage.sync.set({ presentations: updatedPresentations }, () => {});
    }
  }
});

关键说明

  • 用[presentationtitle]作为对象键,实现动态变量键的需求
  • 使用扩展运算符...合并现有presentations数据,避免覆盖已有的其他演示条目
  • 一次性获取presentations和general,减少Chrome存储API的调用次数

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 23:30:49