Accessing JavaScript Properties via a Dot Notation String at Runtime

Problem

You have something like the following object and a string which you would like to use to access a property on said object:

{
  common: {
    de: {
      library: 'Bibliothek',
      manufacturer: 'Hersteller'
    }
  }
}
"common.de.library"

Solution

var accessPropertyViaString = function(object, keys) {
  try {
    return keys.split('.').reduce((prev, curr) => prev[curr], object) || keys;
  } catch (ex) {
    return keys;
  }
};

This function returns the value of the wanted property. If it can’t find the property it will return the input string. Please do not try to solve this problem using eval() for reasons explained in this answer on StackOverflow.

Leave a Reply

Your email address will not be published. Required fields are marked *