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