The issue I am currently encountering in my project involves a complex result object structure, as shown below:
results = {
a : { b : { c : value1 }},
d : value2,
e : { f : value3 }
}
I am looking for a dynamic solution to retrieve a specific value based on a string input. For example:
//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
One challenge is that I do not know beforehand how many levels deep the required value will be (direct key, subkey, sub-subkey, etc.).
My initial approach was to split the string and extract the keys into an array:
const keys = string.split('.') // = ['a','b','c']
However, I am struggling to dynamically access the desired value after this step. One possible solution could involve creating if statements to handle different scenarios based on the number of keys present, but I believe there must be a more efficient and cleaner way to tackle this problem. Any suggestions or ideas?
As reference, the if statement approach would look like:
if (keys.length === 1) {
value = results[keys[0]];
} else if (keys.length === 2) {
value = results[keys[0]][keys[1]];
} // and so on...