如何利用带点符号和索引的路径字符串提取对象数据?
解析带数组索引的路径字符串提取数据
可以通过正则拆分路径片段,再逐段访问对象/数组的方式实现,以下是JavaScript的具体实现:
示例代码
首先定义数据和路径字符串:
// 对应路径里的body对象 const obj = { body: { "recipients": [ { "recipient": "test" } ], "data": "Text message from client", "chatType": "single" } }; // 数据库中存储的路径字符串 const pathStr = "body.recipients[0].recipient";
实现提取函数:
function extractValue(obj, path) { // 用正则提取路径中的所有属性名和数组索引 const pathSegments = path.match(/([^\.\[\]]+)/g); let currentValue = obj; for (const seg of pathSegments) { // 尝试将片段转为数字,判断是否为数组索引 const index = Number(seg); if (!isNaN(index) && Array.isArray(currentValue)) { currentValue = currentValue[index]; } else { currentValue = currentValue[seg]; } // 中途不存在对应值时提前终止 if (currentValue === undefined) break; } return currentValue; }
调用函数获取结果:
const result = extractValue(obj, pathStr); console.log(result); // 输出: "test"
思路说明
- 拆分路径:用正则
/([^\.\[\]]+)/g匹配路径中所有非.、[、]的内容,把body.recipients[0].recipient拆成["body", "recipients", "0", "recipient"]。 - 逐段访问:遍历拆分后的片段,对每个片段判断是否为数组索引(转数字后非NaN且当前值是数组),分别用索引或属性名的方式访问对应值。
- 边界处理:如果中途访问到
undefined,直接终止循环避免报错。
其他语言(如Python、Java)的实现思路类似,核心都是拆分路径片段,区分对象属性和数组索引后逐层访问。
内容的提问来源于stack exchange,提问作者Maykel Esser
相关产品推荐
相关产品推荐

