Access object child properties using a dot notation string [duplicate]

Here’s a naive function I wrote a while ago, but it works for basic object properties:

function getDescendantProp(obj, desc) {
    var arr = desc.split(".");
    while(arr.length && (obj = obj[arr.shift()]));
    return obj;
}

console.log(getDescendantProp(r, "b.b2"));
//-> 99

Although there are answers that extend this to “allow” array index access, that’s not really necessary as you can just specify numerical indexes using dot notation with this method:

getDescendantProp({ a: [ 1, 2, 3 ] }, 'a.2');
//-> 3

Leave a Comment