2

我想使用字符串选择器设置对象属性。我有一个字符串model.name,我有一个对象来存储值。object[model.name]我不想将值存储在其中,而是将其存储在object[model][name].

怎么能用 javascript/jQuery 或 javascript/jQuery 插件来完成呢?

4

1 回答 1

3
function setObjectPathValue(source, path, value) {
    var parts = path.split('.'), len = parts.length, target = source;

    for (var i = 0, part; i < len - 1; i++) {
        part = parts[i];
        target = target[part] == undefined ? (target[part] = {}) : target[part];
    }
    target[parts[len - 1]] = value;
    return target;
}

var obj = {};
setObjectPathValue(obj, "level1.level2.level3.name", "test");
alert(obj.level1.level2.level3.name);
于 2012-07-11T15:31:31.523 回答