1

I have this code

var myObject = {
  prop1: [ 
    'this is prop1:',
    ['answer1', 'prop2'],
    ['answer2', 'prop3']
  ],

  prop2: [ 
    'this is prop2:',
    ['answer1', 'prop1'],
    ['answer2', 'prop3'], 
  ],

  prop3: [ 
    'this is prop3:',
    ['answer1', 'prop1'],
    ['answer2', 'prop2'],
  ]
};

Now let's say I make this variable

var myVar = myObject.prop1;

so suppose I want to console.log(myVar);

It will give me the array prop1 with all its values.

I would like to mutate the variable myVar and change it to:

myVar = myObject.prop2;

I want to do this using the string that are attached next to the answers so basically answer1 to question1 has prop2 as a string.

I want to get that string and convert it as a the property prop2 to call it.

I tried:

var pullProp = myObject.prop1[1][1];  // which is the string prop2

myVar = myObject.pullProp;

console.log(myVar);  // i get undefined
JJJ
  • 32,902
  • 20
  • 89
  • 102
ajmakhl
  • 33
  • 1
  • 6

2 Answers2

1

You could use the content of

myObject.prop1[1][1] // 'prop2'

as key for

myVar = myObject[myObject.prop1[1][1]];

You may have a look for property accessors

Property accessors provide access to an object's properties by using the dot notation or the bracket notation.

Syntax

object.property
object["property"]

var myObject = {
        prop1: ['this is prop1:', ['answer1', 'prop2'], ['answer2', 'prop3']],
        prop2: ['this is prop2:', ['answer1', 'prop1'], ['answer2', 'prop3']],
        prop3: ['this is prop3:', ['answer1', 'prop1'], ['answer2', 'prop2']]
    },
    myVar = myObject.prop1;

console.log(myVar);
myVar = myObject[myObject.prop1[1][1]];
console.log(myVar);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
0

There is no property defined on myObject named pullProp. pullProp is a variable defined at the same scope level as myObject.

What I think you want to achieve is:

myVar = pullProp;
Pineda
  • 7,435
  • 3
  • 30
  • 45