Convert flattened key->value pairs to a nested object

孤者浪人 提交于 2020-01-02 07:13:33

问题


What would be the easiest way to convert the following key->value object "array" to a proper "JSON" style object? Example below would be converting input into graph.

var input = {
    "graph.default.seriesColor" : ["#cccccc", "#3c3c3c"],
    "graph.default.stackSeries" : false,
    "graph.default.title.text" : "Hello!",
    "graph.default.title.show" : false,
    "graph.default.axesDefaults.show" : true,
    "graph.default.axesDefaults.min" : 17,
    "graph.default.axesDefaults.max" : 20,
};

var graph = {
    default: {
        seriesColor: ["#cccccc", "#3c3c3c"],
        stackSeries: false,

        title: {
            text: "Hello!",
            show: false
        },

        axesDefault: {
            show: true,
            min: 17,
            max: 20
        }
    }
};

I considered using eval, however it quickly became complicated in a recursive way.


回答1:


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).



来源:https://stackoverflow.com/questions/11235906/convert-flattened-key-value-pairs-to-a-nested-object

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