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

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

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