Context: I am writing a Redux reducer (although this question is not specific to Redux) for my application settings, which is a nested object. I want to change the settings object using property names that are given dynamically.
Example:
const settings = {
service: {
username: 'TEST',
password: ''
}
}
const settingKey = 'service.username';
console.log(settings[settingKey]);
console.log(eval(`settings.${settingKey}`));
Run codeThe only way I can think of accessing a subobject without using eval is to use a regular expression to split settingKeyinto its component parts:
const match = /(.+)\.(.+)/.exec(settingKey);
console.log(settings[match[1]][match[2]];
const settings = {
service: {
username: 'TEST',
password: ''
}
}
const settingKey = 'service.username';
const match = /(.+)\.(.+)/.exec(settingKey);
console.log(settings[match[1]][match[2]]);
Run codeIt works, but
- It's not beautiful
- It does not work for deeper nested objects.
Is there a way to access the properties of nested objects with a dynamic name without using regular expressions or eval?
source
share