7

Context: I'm writing a Redux reducer (although this question is not Redux-specific) for my app's settings, which is a nested object. I want to modify 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's hardcoded

const settingKey = 'service.username';

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

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

The only way I can think of accessing the subobject without using eval is using a regex to split the settingKey into 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]]);

This works, but

  1. It's ugly
  2. It doesn't work for more deeply nested objects

Is there a way of accessing a nested object's properties with a dynamic name without using regexes or eval?

Marks Polakovs
  • 510
  • 5
  • 18

3 Answers3

5

You can do something like this,

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"

Or you can do it simply using 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"
Rajaprabhu Aravindasamy
  • 66,513
  • 17
  • 101
  • 130
0

Another option that doesn't use eval and works with nested properties.

var settings = {service: {username: 'TEST', password: ''}}
var key = "service.username";
console.log(Function('setting', 'return settings.' + key)(settings));
GOTO 0
  • 42,323
  • 22
  • 125
  • 158
-1

I think you just change one bit:

const settings = {
  service: {
    username: 'TEST',
    password: ''
  }
}
console.log(settings['service'].username);
Thanh Dong
  • 101
  • 1
  • 1
  • 6