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

如何访问JavaScript对象属性名并提取FOI_OMG_101中的101赋值给output.field

问题原因

substring是字符串类型的内置方法,仅能对字符串调用,直接对普通对象dataToInsert调用会触发类型错误,无法得到预期结果。核心逻辑偏差在于没有先获取到需要截取的目标字符串——也就是对象的键名FOI_OMG_101,直接对整个对象做了字符串操作。

正确实现方案

根据业务场景匹配对应写法即可:

  • 已知键名固定为FOI_OMG_前缀加数字的格式,直接写固定截取逻辑:
const dataToInsert = {
  FOI_OMG_101 : {
    name : "jghj.pdf",
    value: "base64"
  }
};

const TARGET_KEY = 'FOI_OMG_101';
const output = {
  // `FOI_OMG_`前缀长度为8,从索引8位开始截取即可拿到末尾数字片段
  field: TARGET_KEY.substring(8),
  fileName: dataToInsert[TARGET_KEY].name,
  value: dataToInsert[TARGET_KEY].value
}
  • 如果键名前缀长度可能变动,但规则固定为「提取键名中最后一个下划线后的数字片段」,且当前对象仅存储这一个目标条目,可以用通用写法,不需要硬编码键名和截取位置:
const dataToInsert = {
  FOI_OMG_101 : {
    name : "jghj.pdf",
    value: "base64"
  }
};

// 取对象的第一个自有键作为目标键
const targetKey = Object.keys(dataToInsert)[0];
const output = {
  // 定位最后一个下划线的位置,往后偏移1位开始截取
  field: targetKey.substring(targetKey.lastIndexOf('_') + 1),
  fileName: dataToInsert[targetKey].name,
  value: dataToInsert[targetKey].value
}
  • 如果对象中可能存储多个条目,需要先匹配到符合FOI_OMG_xxx格式的目标键再做提取,避免取错:
const dataToInsert = {
  other_key: {},
  FOI_OMG_101 : {
    name : "jghj.pdf",
    value: "base64"
  }
};

// 筛选出FOI_OMG_开头的目标键
const targetKey = Object.keys(dataToInsert).find(key => key.startsWith('FOI_OMG_'));
const output = {
  field: targetKey.substring(targetKey.lastIndexOf('_') + 1),
  fileName: dataToInsert[targetKey].name,
  value: dataToInsert[targetKey].value
}

上述代码执行后output.field的值为字符串"101",如果需要数字类型,在截取结果外包一层Number()做类型转换即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.28 13:48:14