将JavaScript对象"树"初始化为任何深度的嵌套对象

njf*_*ife 1 javascript arrays jquery json

基本上我的我正在尝试初始化一个JavaScript对象并让它包含一个带有单个键的空对象.例如:

getOject('one.two.three')
Run Code Online (Sandbox Code Playgroud)

会导致对象:

{one:{two:{three:''}}}
Run Code Online (Sandbox Code Playgroud)

据我所知,除非使用数组表示法,否则无法使用动态键名进行初始化

root[dynamicKey] = 'some variable';
Run Code Online (Sandbox Code Playgroud)

所以我需要循环并根据args的数量初始化每个,然后分配它的值,但语法似乎不允许我以我知道的任何方式这样做.

所以,如果它不是一个循环,它将是这样的:

jsonifiedForm[rootKey] = {};
jsonifiedForm[rootKey][childKeys[0]] = {};
jsonifiedForm[rootKey][childKeys[0]][childKeys[1]] = $input.val();
Run Code Online (Sandbox Code Playgroud)

我想不出一种方法可以做到这一点,我通常不是一个JS人,所以它可能是简单的但我在Google或Stack Overflow上找不到任何东西

先感谢您!

fst*_*nis 5

这个功能应该是你正在寻找的.

function getOject(str) {
    // this turns the string into an array = 'one.two.three' becomes ['one', 'two', 'three']
    var arr = str.split('.');

    // this will be our final object
    var obj = {};

    // this is the current level of the object - in the first iteration we will add the "one" object here
    var curobj = obj;

    var i = 0;
    // we loop until the next-to-last element because we want the last element ("three") to contain an empty string instead of an empty object
    while (i < (arr.length-1)) {
        // add a new level to the object and set the curobj to the new level
        curobj[arr[i]] = {};
        curobj = curobj[arr[i++]];
    }
    // finally, we append the empty string to the final object
    curobj[arr[i]] = '';
    return obj;
}
Run Code Online (Sandbox Code Playgroud)

  • 添加注释以使代码更清晰 (3认同)