Convert flattened key->value pairs to a nested object

℡╲_俬逩灬. 提交于 2019-12-06 04:38:56

For some reason I really felt like writing you a function for this:

function makeObj(input)
{
    var output = {};

    for(var key in input)
    {
        var nodes = key.split('.'), dest = output;

        if(nodes.length < 1)
            continue;

        for(var i = 0; i < (nodes.length - 1); ++ i)
        {
            var node = nodes[i];

            dest = (dest[node] === undefined) ?
                        (dest[node] = {}) : dest[node];
        }

        dest[nodes[nodes.length - 1]] = input[key];
    }

    return output;
}

graph = makeObj(input);

Obviously unlike an eval solution, this will only accept strings in the exact format you described (x.y.z).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!