如何从关键字符串构建嵌套属性

时间:2013-06-24 16:12:16

标签: javascript object nested

var keys1 = ["foo", "moreFoo"],
value1 = "bar",
keys2 = ["foo", "ultraFoo"],
value2 = "bigBar";

我想创建一个可以构建对象的函数:

object {
foo : {moreFoo: "bar", ultraFoo: "bigBar"}
}

我想到了我的每个阵列并执行以下操作:

function recursiveObjectBuild(object, keys, value) {
    var index = 0;
    function loop(object, index) {
        var key = keys[index];
        //Property exists, go into it
        if (key in object) {
            loop(object[key], ++index);
        //Property doesn't exist, create it and go into it
        } else if (index < keys.length-1) {
            object[key] = {};
            loop(object[key], ++index);
        //At last key, set value
        } else {
            object[key] = value;
            return object;
        }
    }
    return loop(object, 0);
}

哪个应该适用于IMO但不适用(无限循环,必须是一个愚蠢的错误,但无法看到它)。

我确信必须有一个更简单的方法

1 个答案:

答案 0 :(得分:1)

尝试以下方法:

function objectBuild(object, keys, value) {
    for (var i = 0; i < keys.length-1; i++) {
        if (!object.hasOwnProperty(keys[i]))
            object[keys[i]] = {};
        object = object[keys[i]];
    }
    object[keys[keys.length-1]] = value;
}

示例用法(see it in action):

var object = {};
objectBuild(object, ["foo", "moreFoo"], "bar");
objectBuild(object, ["foo", "ultraFoo"], "bigBar");
// object --> {foo: {moreFoo: "bar", ultraFoo: "bigBar}}