具有动态名称的嵌套对象属性 [英] Nested object properties with dynamic name

查看:76
本文介绍了具有动态名称的嵌套对象属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

示例:

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

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

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]]);

这样可行,但


  1. 这很丑陋

  2. 它不适用于更深层次的嵌套对象

有没有办法使用动态名称访问嵌套对象的属性而不使用正则表达式或eval?

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

推荐答案

你可以做这样的事情,

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

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"

这篇关于具有动态名称的嵌套对象属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆