Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

144
Views
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 ?

------------- edit ------------------------

also what if i want to set the value for the sections object

something like

function setSectionText(key ,  newText)
{
   sections[key].text = newText ; 
}
about 4 years ago · Santiago Trujillo
1 answers
Answer question

0

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'));
getSection('social.telegram').id = 42;
console.log(sections);
.as-console-wrapper { max-height: 100% !important; top: 0; }

about 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!