1

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...
Ivo
  • 2,308
  • 1
  • 13
  • 28

1 Answers1

2

You can use split and reduce to achieve this

let results = {
  a : { b : { c  : 'value1' }},
  d : 'value2',
  e : { f : 'value3' }
  }
  
function getValue(str) {
  return str.split('.').reduce((o, d) => o[d], results)
}

console.log(getValue('a.b.c'))

console.log(getValue('e.f'))
Nitish Narang
  • 4,124
  • 2
  • 15
  • 22