将展平的键 - >值对转换为嵌套对象 [英] Convert flattened key->value pairs to a nested object

查看:65
本文介绍了将展平的键 - >值对转换为嵌套对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

将以下key-> value对象array转换为正确的JSON样式对象的最简单方法是什么?下面的示例将输入转换为图形。

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
        }
    }
};

我考虑使用eval,但它很快就会以递归的方式变得复杂。

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

推荐答案

出于某种原因,我真的想为你写一个函数:

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

显然不像 eval 解决方案,这将是只接受您描述的确切格式的字符串(xyz)。

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

这篇关于将展平的键 - >值对转换为嵌套对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆