Home > database >  Accessing Hierarchy Data in an Object Javascript
Accessing Hierarchy Data in an Object Javascript

Time:02-25

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";
}


CodePudding user response:

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);
  • Related