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

176
Views
Acceder a datos de jerarquía en un objeto Javascript

Necesito acceder al valor de identificación en un objeto Javascript para mostrar un mensaje simple de que el usuario tiene membresía si el valor de identificación es igual a un valor específico.

Recibo el mensaje de error de tipo no detectado no definido 'id'

En la consola se muestra como

 subscriptions: Array(1) 0: // COMMENT Don't know what this is autoRenew: false canRenew: false expiryDate: "2022-10-26T00:00:00" membership: id: "819AGBHDRLQHNHPHKKMPKLGPMDRDTDMVL"

Supongo que JSON equivalente es algo como:

 subscriptions { 0 { membership: { id: "819AGBHDRLQHNHPHKKMPKLGPMDRDTDMVL" } } }

Mi código Javascript

 const userObj3 = userObj['subscriptions']['0']['membership']['id']; if (userObj3 = "819AGBHDRLQHNHPHKKMPKLGPMDRDTDMVL") { greeting = "You have membership"; }
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Sus suscripciones son una matriz, también su comparación dentro de if es incorrecta y debería ser == o === , también podría usar la anotación de puntos para atravesar el objeto en lugar de usar corchetes en cada tecla.

Usar el índice como una cadena en lugar de un número no está mal, simplemente no es una buena práctica.

Es posible que desee pensar en recorrer las suscripciones en lugar de usar el índice directo en caso de que haya varias suscripciones. Pero eso solo depende de cómo estructure sus datos y depende de usted.

 const userObj = { subscriptions: [ { autoRenew: false, canRenew: false, expiryDate: '2022-10-26T00:00:00', membership: { id: '819AGBHDRLQHNHPHKKMPKLGPMDRDTDMVL' } }, { autoRenew: true, canRenew: false, expiryDate: '2022-10-26T00:00:00', membership: { id: '201AGBHDRLQHNHPHKKMPKLGPMDRDTDMVL' } } ] }; let greeting = "You're not a member"; userObj.subscriptions.forEach((sub) => { if (sub.membership.id === '201AGBHDRLQHNHPHKKMPKLGPMDRDTDMVL') { greeting = "You're a member"; } }); console.log(greeting);
about 4 years ago · Juan Pablo Isaza 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!