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.
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"));
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With