In javascript how can I dynamically get a nested property of an object

You can use a deep access function based on a string for the path. Note that you can’t have any periods in the property names.

function getPropByString(obj, propString) {
  if (!propString)
    return obj;

  var prop, props = propString.split('.');

  for (var i = 0, iLen = props.length - 1; i < iLen; i++) {
    prop = props[i];

    var candidate = obj[prop];
    if (candidate !== undefined) {
      obj = candidate;
    } else {
      break;
    }
  }
  return obj[props[i]];
}

var obj = {
  foo: {
    bar: {
      baz: 'x'
    }
  }
};

console.log(getPropByString(obj, 'foo.bar.baz')); // x
console.log(getPropByString(obj, 'foo.bar.baz.buk')); // undefined

If the access string is empty, returns the object. Otherwise, keeps going along access path until second last accessor. If that’s an ojbect, returns the last object[accessor] value. Otherwise, returns undefined.

Leave a Comment