0

I'm trying to access the properties of easeSegmentNameMap using:

easeSegmentNameMap["EMAIL_ENGAGED"].text

I'm getting undefined, it works if I use:

easeSegmentNameMap["EMAIL_ENGAGED"].name

var easeSegmentNameMap = {
  "EMAIL_ENGAGED": {
    name: "emailEngaged"
  },
  "EMAIL_INACTIVE": {
    name: "emailInactive"
  },
  "LIKELY_TO_THRIVE": {
    name: "likelyToThrive"
  },
  "MOST_VALUABLE_SUBSCRIBERS": {
    name: "mostValuableSubscribers"
  },
  "NEARLY_INACTIVE": {
    name: "nearlyInActive"
  },
  "NEVER_ACTIVATED": {
    name: "neverActivated"
  },
  "QUESTION_MARKS": {
    name: "questionMarks"
  }
};

var text = "name";
alert(easeSegmentNameMap["EMAIL_ENGAGED"].text);

Output:

undefined

What am I doing wrong?

LogicalBranch
  • 4,248
  • 4
  • 21
  • 54

3 Answers3

1

Try this:

alert(easeSegmentNameMap["EMAIL_ENGAGED"][text]);

text is a variable and has to be interpolated.

Bryan Scott
  • 4,337
  • 1
  • 9
  • 12
1

You can't access

var text="name";
alert(easeSegmentNameMap["EMAIL_ENGAGED"].text);

the text is still the property, in this case, it's not the variable. If you wanted to access the variable you should access like this:

alert(easeSegmentNameMap["EMAIL_ENGAGED"][text]);
LogicalBranch
  • 4,248
  • 4
  • 21
  • 54
arielb
  • 367
  • 3
  • 10
0

Just need to use [] bracket notation. whenever you need to access any object property using variable you need to use [] notation.

var easeSegmentNameMap = {
  "EMAIL_ENGAGED": {
    name: "emailEngaged"
  },
  "EMAIL_INACTIVE": {
    name: "emailInactive"
  },
  "LIKELY_TO_THRIVE": {
    name: "likelyToThrive"
  },
  "MOST_VALUABLE_SUBSCRIBERS": {
    name: "mostValuableSubscribers"
  },
  "NEARLY_INACTIVE": {
    name: "nearlyInActive"
  },
  "NEVER_ACTIVATED": {
    name: "neverActivated"
  },
  "QUESTION_MARKS": {
    name: "questionMarks"
  }
};

var text = "name";
console.log(easeSegmentNameMap["EMAIL_ENGAGED"][text]);
LogicalBranch
  • 4,248
  • 4
  • 21
  • 54
Code Maniac
  • 35,187
  • 4
  • 31
  • 54