Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Get the Value of nested JavaScript object property by string key [duplicate]

Tags:

javascript

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.

like image 867
Shan Khan Avatar asked Dec 13 '15 23:12

Shan Khan


1 Answers

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"));
like image 80
madox2 Avatar answered Nov 11 '22 05:11

madox2