eclipseIzHere eclipseIzHere - 1 month ago 5
Javascript Question

How to access property in object according to array

so i have an array like this:

var arr=[one, lol];


and an object like this

var obj={
one:{
lol:11234
}
}


How do I make it so if i do obj[lol] then it will print out 11234? Keep in mind I don't know how long the array is and answers like console.log(obj[one][lol]) doesn't work. Thanks in advance.

Answer

You can store the previous property's value (initially obj) and continue to loop until end of array like so:

var arr = ['one', 'two', 'three'];

var obj = {
  one: {
    two: {
      three: 11234
    }
  }
}

var currentProp = obj;

for(var i = 0; i < arr.length; i++) {
  currentProp = currentProp[arr[i]];
}

console.log(currentProp);

The above code will start at the object obj, then loop until the array's length, and reassign currentProp to the next property in the array as it goes. In this case, this is what it does:

  • First iteration, access obj[arr[0]], which is one, and assign it to currentProp
  • Second iteration, access obj[arr[0]][arr[1]] or one[arr[1]], which is two, and assign it to currentProp
  • Third iteration, access obj[arr[0]][arr[1]][arr[2]] or two[arr[2]], which is three, and assign it to currentProp. Loop then terminates as it has reached end of the list.

In the end, the value of the last property will be in currentProp, and will correctly output 11234.