In my project I am facing the following issue. I have a quite complexe result object similar to this :
results = {
a : { b : { c : value1 }},
d : value2,
e : { f : value3 }
}
I would like to get a dynamic way to get a specific value based on astring such :
//example 1
const string = '.a.b.c';
const value = results['a']['b']['c']; // = value1
// example 2
const string2 = '.e.f';
const value2 = results['e']['f']; // = value3
I never know in advance how "deep" the value I would need will be. (direct key, subkey, subsubkey...)
I started by spliting my string and gettings the keys in an array:
const keys = string.split('.') // = ['a','b','c']
but then I don't see how dynamically getting the value I need. I could make an if statement for the case with 1, 2, 3 or 4 (or more) keys but I am sure there could be a dynamic cleaner way to manage this. Someone has any idea ?
For info the if statement would be
if (keys.length === 1) {
value = results[keys[0]];
} else if (keys.length === 2) {
value = results[keys[0]][keys[1]];
} // and so on...