I have
data =
{
'first': {
'number': 1,
'text': 'Ya.'
},
'second': {
'number': 10,
'text': 'Da.'
}
};
And I really want to access it like:
number = data['first.number'];
Actually in a more flexible way, like:
numberOrText = data[memberName+'.'+propertyName];
Is there any lightweight library, or snippet you can suggest? This is - https://github.com/martinvl/KVCObject - so cool, but a bit overhead for this.
You can easily resolve keypath with reduce function, without using any library.
First, we are creating an example object, called target, with some nested objects inside :
const target = {
foo: {
bar: {
example: 65
}
}
};
Then, we define a variable keypath containing keypath string : we want to access example property inside our target object.
const keypath = 'foo.bar.example';
The hard work begins today ! Keypath is splitted by dot separator and we obtain a keys array. We iterate over this array (with reduce function) and for each iteration, we return a new object.
const result = keypath.split('.').reduce((previous, current) => previous[current], target);
Finally, result variable value is 65. It works !
With lodash there is a simple method for doing this.
_.get()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With