Here I have an issue(sample code below). How to get rid of undefined? In my case I can use only one variable like
object[dynamicKey]
but if the key is deeper in object then first level I get errors.
object = {
name: 'peter',
kidsNames: {
name: 'carlos',
}
}
dynamicKey1 = 'name';
dynamicKey2 = 'kidsNames.name';
console.log(object[dynamicKey1]); // 'peter'
console.log(object[dynamicKey2]); // undefined ???
I want a solution in pure JavaScript
SOLUTION:
Thanks for the help!
With your help guys I came up with solution like:
const getProp = (obj, prop) => {
return prop.split('.').reduce((r, e) => {
return r[e];
}, obj);
};
getProp(object, dynamicKey2) // 'carlos'
So now you it doesent matter how deep into object you need to go it always gives you the right value.