Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

147
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda