Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

151
Vistas
pasar la clave de propiedad para el objeto anidado a una función para devolver ese valor de propiedad

tengo un objeto anidado como este

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

quiero tener una función que me dé cada sección pasándole la clave de propiedad

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

esto funciona para text y link pero si quiero social.telegram esto no funcionará, ¿hay alguna forma de resolver esto sin algún tipo de bucle de secciones?

------------- editar ------------------------

también, ¿qué pasa si quiero establecer el valor para el objeto de las sections ?

algo como

 function setSectionText(key , newText) { sections[key].text = newText ; }
about 4 years ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

0

Debe separar la clave y obtener los objetos externos e internos hasta obtener el resultado deseado.

 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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda