-2

Am having an object like:

var myObj={
    id: 1,
    name: "John",
    parentName: "Peter"
}

But while processing this JSON I'm comparing with some logic where I'm not able to get the key name to be compared since I'm assigning the key name to be compared to another variable:

Example:

This is the logic:

If I want to get the value of parentName say "Peter".My logic compares by having the parentName stored in another variable say dummyVariable.If so I'm fetching the value of parent Name like

 var dummyVariable=parentName;

 var parentValu=myObj.dummyVariable; //which leads to a undefined state .

How can I get the value of parentName if I use a different variable,in this case dummyVariable?

Satpal
  • 132,252
  • 13
  • 159
  • 168
forgottofly
  • 2,729
  • 11
  • 51
  • 93

2 Answers2

2

I think what you want is this:

var myObj={
    id: 1,
    name: "John",
    parentName: "Peter"
}

Then:

var result = myObj['parentName'];  
// result now equals "Peter"

or

var key = 'parentName';
var result = myObj[key];
// result now equals "Peter"
Chris Charles
  • 4,406
  • 17
  • 31
0

the approach you might want to try is myObj[dummyVariable]

Max Bumaye
  • 1,017
  • 10
  • 17