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.

0

1 Answer 1

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"));
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.