Nested object properties with dynamic name

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: ''
  }
}

// Normally this would be passed by Redux, but for the purposes of this exercise it hardcoded

const settingKey = 'service.username';

console.log(settings[settingKey]); // undefined

console.log(eval(`settings.${settingKey}`)); // works, but bad
Run code

The 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 code

It 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?

+4
source share
3

- ,

var settings = {service: {username: 'TEST', password: ''}}
var key = "service.username";

function getValue(obj, keys){
  keys.split(".").forEach(function(itm){
    obj = obj[itm];
  });
  return obj;
}

getValue(settings, key); //"TEST"

Array#reduce,

var settings = {service: {username: 'TEST', password: ''}}
var key = "service.username", result = key.split(".").reduce((a,b) => a[b], settings);
console.log(result); // "TEST"
+3

, eval .

var settings = {service: {username: 'TEST', password: ''}}
var key = "service.username";
console.log(Function('setting', 'return settings.' + key)(settings));
0

I think you just change one bit:

const settings = {
  service: {
    username: 'TEST',
    password: ''
  }
}
console.log(settings['service'].username);
-1
source

Source: https://habr.com/ru/post/1654963/


All Articles