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

178
Vistas
Accessing Hierarchy Data in an Object Javascript

I need to access the id value in a Javascript object to display a simple message that the user has membership if the id value equals a specific value.

I'm getting Uncaught Type Error not defined 'id' message

In the console it's displayed as

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

I'm assuming equivalent JSON is something like:

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

My Javascript Code

const userObj3 = userObj['subscriptions']['0']['membership']['id'];

if (userObj3 = "819AGBHDRLQHNHPHKKMPKLGPMDRDTDMVL") {
  greeting = "You have membership";
}


about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

Your subscriptions are an array, also your comparison inside the if is incorrect and should be == or ===, you could also use dot annotation to traverse the object instead of using brackets on every key.

Using the index as a string instead of a number isn't really wrong, it's just not a good practice.

You might want to think about looping through the subscriptions instead of using the direct index just in case there's multiple subscriptions. But that just depends on how you structure your data and is kinda up to you.

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 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