【问题标题】:Dynamically retrieving variable from chained objects从链式对象中动态检索变量
【发布时间】:2012-07-19 13:45:33
【问题描述】:

我无法弄清楚如何使用类似的函数访问多级深层对象中的变量

getLanguageVariable("form.passwordSwitch.disabled");

下面的对象作为样本

var language = {
    "de": {
        "form": {
            "passwordSwitch": {
                "enabled": "Der Klartext-Modus ist aus. Aktivieren?",
                "disabled": "Der Klartext-Modus ist an. Deaktivieren?"
            }
        }
    }
}

试图在点字符处拆分字符串,然后创建一个字符串表示

language["de"]["form"]["passwordSwitch"]["enabled"]

用于访问对象及其属性。我使用了这段代码:

var stack = variableIdentifier.split(".");
var reference = "";

for (i = 0; i < stack.length; i++) {
    if (i == 0) reference += stack[i];
    else reference += "[\"" + stack[i] + "\"]";
}

任何线索如何动态访问对象的属性,如果你不知道它有多深?

【问题讨论】:

标签: javascript


【解决方案1】:

几天前我在 python 中实现了相同的功能。基本上,当您不知道对象有多深时,请使用递归模式

function getPath(obj, path)
{
    path = path.split('.');
    return _getpath(obj, path);
}

function _getPath(obj, path)
{
    if(!path.length)
        return obj;

    p = path.shift();

    if(obj[p])
        return _getPath(obj[p], path);

    return undefined;
}

【讨论】:

  • 谢谢@jtlebi。当然,这就是递归。上面马特的例子用更少的代码解决了这个问题。虽然你的例子更直观。
  • 感谢您的积极反馈。如果您认为这两个答案的质量都很好,也许您可​​以考虑对它们进行投票?
  • 一旦我获得了足够的声望,我就会这样做。再次感谢。
【解决方案2】:

你可以这样做;

function getLanguageVariable(path) {
    // I don't know how you determine "de", but this should be
    // easy to customise
    var next = language.de;

    // Make path = ["form","passwordSwitch","disabled"];
    path = path.split(/\./);

    // Loop over path, and for each pass, set next to the next key
    // e.g. next = next["form"];
    //      next = next["passwordSwitch"]
    //      next = next["disabled"]
    while (path.length && (next = next[path.shift()]) && typeof next === "object" && next !== null);

    // Check we have used all the keys up (path.length) and return
    // either undefined, or the value
    return path.length ? undefined : next;
}

关于未来的信息,请注意您拥有的是通过 Object Literal Syntax 定义的 Object,而根本不是 JSON;欲了解更多信息,请参阅What is the difference between JSON and Object Literal Notation?

【讨论】:

  • 哇。谢谢你。这对我来说就像魔术一样。永远不会像您建议的那样使用while 进行递归。像魅力♥一样工作。并感谢您指出 JSON 和 Object Literal Notation 之间的区别!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-11-28
  • 1970-01-01
  • 2011-09-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多