将嵌套对象的属性键传递给函数以返回该属性值



我有一个类似的嵌套对象

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'} , 
}
}

我想要一个函数,通过将属性密钥传递给来给我每个部分

function getSection(key ){
console.log(sections[key]);
}

这适用于textlink,但如果我想要social.telegram,这就不起作用有什么方法可以解决这个问题而不需要循环抛出部分吗?

-------------编辑-----------------------

如果我想设置sections对象的值,该怎么办

类似的东西

function setSectionText(key ,  newText)
{
sections[key].text = newText ; 
}

您需要分离键并获取外部和内部对象,直到得到所需的结果。

function getSection(key) {
return key
.split('.')
.reduce((o, k) => o?.[k], sections);
}
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' } } };
console.log(getSection('social.telegram'));
getSection('social.telegram').id = 42;
console.log(sections);
.as-console-wrapper { max-height: 100% !important; top: 0; }

最新更新