7

I want to get a value from within a nested JavaScript object by this key.

var t = "cont.model.Inspection.InspectionName";

How to get the nested object values by string key directly?

I have tried the eval(t) but its giving null but this key has value "A" when run on console.

Shan Khan
  • 9,667
  • 17
  • 61
  • 111

1 Answers1

15

You can use helper function to achieve this, e.g.:

var data = {
    cont: {
        model: {
            Inspection: {
                InspectionName: "Hello world"
            }
        }
    }
};

function getNestedValue(obj, key) {
    return key.split(".").reduce(function(result, key) {
       return result[key] 
    }, obj);
}

console.log(getNestedValue(data, "cont.model.Inspection.InspectionName"));
madox2
  • 49,493
  • 17
  • 99
  • 99