简体   繁体   中英

passing property key for nested object to a function to return that property value

i have a nested object like this

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

i want to have a function giving me each section by passing property key to it

function getSection(key ){

   console.log(sections[key]);
}

this works for text and link but if i want social.telegram this wont work is there any way to solve this without some sort of looping throw sections?

You need to separate the key and get the outer and inner objects until the wanted result.

 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'));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM