0

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

bluray
  • 1,875
  • 5
  • 36
  • 68
  • Do you want to do a kind of property file? – Leonardo Venoso Jul 27 '17 at 09:37
  • Exactly. But i need to properties are in "namespaces" (parent properties). And I need to get value using string path in this structure – bluray Jul 27 '17 at 09:45
  • Possible duplicate of [Accessing nested JavaScript objects with string key](https://stackoverflow.com/questions/6491463/accessing-nested-javascript-objects-with-string-key) – Saravana Jul 27 '17 at 10:19
  • You should rearrange your solution like let properties = {"prop1.prop11.prop111" = "hello ", "prop1.prop12" = {...}}; – Leonardo Venoso Jul 27 '17 at 10:59

1 Answers1

1

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
José Quinto Zamora
  • 2,070
  • 12
  • 15