1

Lets say I have an array:

var array = [
  {
   key1: {
     underkey1: {
       "somekey":"someValue"
     }
   },
  }
];

I know I can reach for key1 like this:

var theVar = "key1";
array[theVar];

But I want to reach underkey1 with one variable, like:

var theVar = "key1.underkey1";

From what I have tried I get undefined.

How can it be done?

2 Answers2

0

You can split that string into array of keys and then use reduce() to reach nested value.

var array = [{key1: {underkey1: "somevalue"},}];

var val = 'key1.underkey1'
  .split('.')
  .reduce((r, e, i, arr) => {
    return r[e] || (arr[i+1] ? {} : undefined)
  }, array[0])
  
console.log(val)
Nenad Vracar
  • 118,580
  • 15
  • 151
  • 176
-1

try following:

var array = [
    {
        key1: {
            underkey1: "somevalue"
        },
    }
];

var theVar = "key1";
theVar2 = "underkey1"
array[0][theVar][theVar2];
Tim Schmidt
  • 1,297
  • 1
  • 15
  • 30
Shyam
  • 1,364
  • 7
  • 13