如何使用格式化字符串访问JavaScript对象中的SUB属性

How to use a formatted string to access SUB properties in a JavaScript object?

本文关键字:SUB 属性 对象 JavaScript 何使用 格式化 字符串 访问      更新时间:2023-09-26

为了实现可重用代码,我试图通过使用"foo.bar.sub"之类的字符串来访问属性,从而避免对数千个复杂对象进行硬编码。

现在,我很快就找到了一个简单的算法,用于获取属性的值,如下所示:

getValueForPath : function(path) {
    var pathArray = path.split('.'),
        modelCopy = this;
    while (pathArray.length > 0) {
        modelCopy = modelCopy[pathArray.shift()];
    }
    return modelCopy;
},

但是,这只会返回属性的值,而不允许我设置属性的值。所以这只是问题的一半。理想情况下,我需要一种方法,对于给定的路径,返回属性本身,我不确定这在JavaScript中是否可能(但我不是JavaScript专家),或者我需要第二个函数来设置给定路径的属性,但我至今无法解决这个问题。

有什么想法吗?

如果您不想使用其他函数,可以使用

getValueForPath("foo.bar").sub = something;

或者,

setValueForPath: function(path, val) {
    var pathArray = path.split('.'),
        modelCopy = this;
    while (pathArray.length > 1) {
        modelCopy = modelCopy[pathArray.shift()];
    }
    return modelCopy[pathArray[0]] = val;
}
getValueForPath("foo.bar.sub", something);

同时考虑统一两个功能:

accessValueForPath: function(path, val) {
    var pathArray = path.split('.'),
        modelCopy = this,
        b = val!==void 0;
    while (pathArray.length > b) {
        modelCopy = modelCopy[pathArray.shift()];
    }
    return b ? modelCopy[pathArray[0]] = val : modelCopy;
}
accessValueForPath("foo.bar.sub"); // read
accessValueForPath("foo.bar.sub", something); // write