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

如何从对象中获取以字符串形式指定的键对应的值

根据路径从对象中获取对应值的实现方法

给定如下对象:

const lead = {
  companies: [{
    schoolName: "ABC",
    education: "Graduation"
  }, {
    schoolName: "DEF",
    education: "Graduation2"
  }],
  hello: 'world',
  education: {
    graduation: 'true',
  },
  nameArray: ['hello', 'world']
}

以及前端传入的路径字符串 companies[0].schoolName,需要实现方法验证路径对应值是否存在,存在则返回该值。

实现思路

把路径字符串拆解为一个个访问节点,比如将companies[0].schoolName拆分为['companies', '0', 'schoolName'],随后逐层遍历对象/数组,每一步都检查当前节点是否存在,避免因访问不存在属性报错,最终返回目标值。

代码实现

function getValueByPath(obj, path) {
  // 拆分路径,过滤空节点,处理数组下标格式(如[0])
  const keys = path.split(/[\.\[\]]/).filter(key => key.trim() !== '');
  let current = obj;
  
  for (const key of keys) {
    // 检查当前节点是否合法:非空,数组下标需为有效数字
    if (current == null || (Array.isArray(current) && isNaN(Number(key)))) {
      return undefined;
    }
    // 数组下标转为数字,对象直接用属性名
    const accessKey = Array.isArray(current) ? Number(key) : key;
    current = current[accessKey];
    if (current == null) {
      return undefined;
    }
  }
  return current;
}

// 测试有效路径
const validResult = getValueByPath(lead, 'companies[0].schoolName');
console.log(validResult); // 输出 "ABC"

// 测试无效路径
const invalidResult = getValueByPath(lead, 'companies[2].schoolName');
console.log(invalidResult); // 输出 undefined

说明

  • 兼容对象属性、数组下标两种路径格式,比如nameArray[1]、education.graduation均可正确解析
  • 全程做存在性校验,避免出现Cannot read properties of undefined类型报错
  • 路径无效或对应值不存在时返回undefined,存在则返回对应值

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 20:25:26