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

如何通过字符串形式的嵌套键动态获取JSON对象的值?

解决JSON嵌套属性动态查询问题

问题描述

给定JSON字符串和由点分隔的嵌套键查询数组,需要为每个查询获取对应JSON对象的值。例如:
示例JSON字符串:

const JSONtext = `{"Student":{"Name":"John","Age":"15"},"Class":"10"}`;

查询数组:

const queries = ["Student.Name","Student.Age", "Class"];

预期输出:John、15、10

当前遇到的问题:直接使用myObj.query会返回undefined,无法动态获取深层嵌套属性值,需要支持任意深度的JSON结构(如{"c":{"mf":{"he":"k"}},"p":"q"})及对应查询(如["c.mf.he", "p"])。

解决方案

核心思路是将查询字符串按.分割成键数组,然后逐层遍历JSON对象获取对应值。可以通过Array.prototype.reduce实现高效的嵌套属性访问,同时处理属性不存在的情况。

完整代码实现

// 解析JSON字符串为JavaScript对象
const JSONtext = `{"Student":{"Name":"John","Age":"15"},"Class":"10"}`;
const queries = ["Student.Name","Student.Age", "Class"];
const deepJSONtext = `{"c":{"mf":{"he":"k"}},"p":"q"}`;
const deepQueries = ["c.mf.he", "p", "nonexistent.key"];

function getNestedValue(obj, keyPath) {
  // 将键路径按点分割成数组
  const keys = keyPath.split('.');
  // 逐层遍历对象,获取最终值
  return keys.reduce((currentObj, key) => {
    // 若当前层级不存在,返回undefined(可自定义默认值)
    return currentObj?.[key];
  }, obj);
}

// 处理普通嵌套场景
const parsedObj = JSON.parse(JSONtext);
const results = queries.map(query => getNestedValue(parsedObj, query));
console.log(results); // 输出: ["John", "15", "10"]

// 处理深层嵌套场景
const deepParsedObj = JSON.parse(deepJSONtext);
const deepResults = deepQueries.map(query => getNestedValue(deepParsedObj, query));
console.log(deepResults); // 输出: ["k", "q", undefined]

代码说明

  • JSON.parse():将JSON字符串转换为可操作的JavaScript对象。
  • getNestedValue函数:接收目标对象和键路径字符串,通过split('.')拆分路径,再用reduce逐层访问对象属性。
  • 容错处理:使用可选链操作符?.避免属性不存在时抛出错误,默认返回undefined,也可替换为自定义默认值(比如currentObj?.[key] ?? '默认值')。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 08:50:30