[英]passing property key for nested object to a function to return that property value
我有一個像這樣的嵌套 object
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 通過傳遞屬性密鑰給我每個部分
function getSection(key ){
console.log(sections[key]);
}
這適用於text
和link
,但如果我想要social.telegram
這將不起作用,有沒有辦法在沒有某種循環拋出部分的情況下解決這個問題?
您需要分離鍵並獲取外部和內部對象,直到想要的結果。
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'));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.