bluray bluray - 1 year ago 119
TypeScript Question

Typescript easy way to get property from inners objects

i have this object structure:

let data = {
prop1 = {
prop11 = {
prop111 = 'hello'
},
prop12 = {...}
},
prop2= {...}
}


And i have this formated string:
'data.prop1.prop11.prop111'


I would like to map this string to data structure and get value (in this example 'hello'). Its general data structure, I dont know how names of property is in (not solid property names).
It is easy way how to do it? Probably I need parse string to array and then?

Thank you for advices

Answer Source

I created a similar function few months ago,

Let's say you have this object:

var obj = {
    data: {
        prop1: {
            prop11: {
                prop111: 'hello'
            },
            prop12: "12"
        },
        prop2: "1"
    }
}

Then, you can use this function (JavaScript):

function getDescendantProp(obj, desc) {
    var arr = desc.split(".");
    if (arr.length > 0 && arr[0] !== "") {
        while (arr.length) {
            var name = arr.shift();
            if (name in obj) {
                obj = obj[name];
            } else {
                console.warn('[getDescendantProp] - ' + name + ' property does not exists.');
                return undefined;
            }
        }
    }
    return obj;
}

TypeScript Code:

function getDescendantProp(obj: {[key: string]: {}}, desc: string) {
    if (obj === null || obj === undefined || desc === "") {
        return undefined;
    }
    const arr: string[] = desc.split(".");
    if (arr.length > 0 && arr[0] !== "") {
        while (arr.length) {
            const name: string | undefined = arr.shift();
            if ((typeof name === "string") && (name in obj)) {
                obj = obj[name];
            } else {
                console.warn("[getDescendantProp] - " + name + " property does not exists.");
                return undefined;
            }
        }
    }
    return obj;
}

And use it:

getDescendantProp(obj, "data.prop1.prop11.prop111") // hello
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download