如何通过嵌套属性键获取/设置嵌套对象属性(无需循环)?
问题描述
现有如下嵌套对象:
const sections = { text : {id : 1 , text: 'something' }, link : {id : 2 , text: 'something' , 'href' : 'http://example.com' }, social : { telegram : {id : 3 , text : 'my telegram' , 'address' : '@mytelegram'} , twitter : {id : 4 , text : 'my twitter' , 'address' : '@mytwitter'} , } }
需要实现两个函数:
getSection(key):传入属性键获取对应部分,目前仅支持text、link这类一级键,传入social.telegram这类嵌套键时无法工作,希望找到无需遍历整个对象的解决方法。setSectionText(key, newText):修改对应部分的text属性,同样需要支持嵌套属性键。
解决方案
1. 支持嵌套键的getSection函数
通过将嵌套键按.拆分,用Array.reduce沿着键路径逐步访问对象属性,这种方式仅遍历键路径的层级,而非整个对象:
function getSection(key) { return key.split('.').reduce((current, part) => { return current?.[part]; // 可选链避免路径不存在时报错 }, sections); } // 测试示例 console.log(getSection('text')); // {id: 1, text: 'something'} console.log(getSection('social.telegram')); // {id: 3, text: 'my telegram', address: '@mytelegram'} console.log(getSection('invalid.path')); // undefined(无报错)
如果环境不支持ES2020的可选链操作符,可改用兼容写法:
function getSection(key) { return key.split('.').reduce((current, part) => { return current && current[part] ? current[part] : undefined; }, sections); }
2. 支持嵌套键的setSectionText函数
同样拆分键路径,先定位到目标对象的父层级,再修改对应text属性,同时处理路径不存在的情况:
function setSectionText(key, newText) { const parts = key.split('.'); // 定位到目标对象的父级 let current = sections; for (let i = 0; i < parts.length - 1; i++) { current = current?.[parts[i]]; if (!current) break; } // 确认路径有效后修改text const targetKey = parts[parts.length - 1]; if (current && current[targetKey]) { current[targetKey].text = newText; } else { console.error('指定的路径不存在'); } } // 测试示例 setSectionText('text', '更新后的文本'); console.log(sections.text.text); // '更新后的文本' setSectionText('social.twitter', '我的新推特简介'); console.log(sections.social.twitter.text); // '我的新推特简介'
内容的提问来源于stack exchange,提问作者hretic
相关产品推荐
相关产品推荐

