具有动态名称的嵌套对象属性

Mar*_*ovs 7 javascript

上下文:我正在为我的应用程序设置编写一个 Redux reducer(尽管这个问题不是 Redux 特定的),它是一个嵌套对象。我想使用动态给出的属性名称修改设置对象。

例子:

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
Run Code Online (Sandbox Code Playgroud)

我能想到在不使用 eval 的情况下访问子对象的唯一方法是使用正则表达式将其拆分settingKey为其组成部分:

const match = /(.+)\.(.+)/.exec(settingKey);
console.log(settings[match[1]][match[2]];
Run Code Online (Sandbox Code Playgroud)

const match = /(.+)\.(.+)/.exec(settingKey);
console.log(settings[match[1]][match[2]];
Run Code Online (Sandbox Code Playgroud)

这有效,但是

  1. 它很丑
  2. 它不适用于更深层嵌套的对象

有没有一种方法可以在不使用正则表达式或 eval 的情况下使用动态名称访问嵌套对象的属性?

Raj*_*amy 5

你可以做这样的事情,

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"
Run Code Online (Sandbox Code Playgroud)

或者你可以简单地使用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"
Run Code Online (Sandbox Code Playgroud)