如何实现根据指定路径获取嵌套数据对象中的值?
实现findNestedValue函数的思路与代码建议
问题背景
我们正在处理从JSON字符串解析而来的数据对象,已完成10个练习中的8个,目前卡在第9个。任务要求实现findNestedValue函数,根据给定路径查找并返回嵌套数据对象中的对应值。
初始函数模板
function findNestedValue(obj, path) { }
示例数据对象
const sampleData = { people: [{ name: 'Alice', age: 30, }, { name: 'Bob', age: 25, }, { name: 'Charlie', age: 35, }], city: 'New York', year: 2023, };
测试用例(来自test.js)
test('findNestedValue should find and return the value at the given nested path', () => { expect(findNestedValue(sampleData, 'people[0].name')).toBe('Alice'); expect(findNestedValue(sampleData, 'city')).toBe('New York'); });
我尝试的未完成代码
for (let key in obj) { if (Array.isArray(obj[key])) { for (let i = 0; i < obj[key].length; i++) { if (obj[key][i] === path) else { if (obj[key] === path)
实现思路与代码建议
核心思路是把路径字符串拆分成逐层访问的节点,再沿着节点一步步深入对象/数组:
- 解析路径:将
people[0].name这类格式的路径拆分成['people', '0', 'name']的节点数组,处理对象键(.分隔)和数组索引([数字]包裹)两种格式。 - 逐层访问:从初始对象开始,依次用节点访问对应的值,中途若遇到不存在的节点则返回
undefined。
具体实现代码:
function findNestedValue(obj, path) { // 拆分路径,过滤空值得到节点数组 const nodes = path.split(/\[|\]|\./).filter(node => node !== ''); let current = obj; for (const node of nodes) { // 数组类型用数字索引访问 if (Array.isArray(current)) { current = current[Number(node)]; } else { current = current[node]; } // 中途找不到值直接终止 if (current === undefined) break; } return current; }
代码说明
- 正则
/\[|\]|\./会把路径中的[、]、.都作为分隔符,拆分后过滤空字符串,得到干净的访问节点。 - 遍历节点时,区分数组和对象的访问方式,数组需要把节点转成数字索引。
- 若中途
current变为undefined,说明路径无效,直接返回undefined。
这个实现可以通过给定的测试用例,也能处理更多场景,比如findNestedValue(sampleData, 'people[2].age')会返回35,findNestedValue(sampleData, 'year')返回2023。
你的尝试思路偏差在于,不是去匹配对象中的键等于完整路径,而是要把路径拆分成一步一步的访问步骤,逐层深入目标值。
内容的提问来源于stack exchange,提问作者Litmanen84
相关产品推荐
相关产品推荐

