首页 > 解决方案 > 如何将具有表示数字列表(“1.1.1”)的键的对象转换为多维数组

问题描述

让我们考虑一下我有以下普通对象:

var numberedList = {
    "1": "Text of 1",
    "1.1": ["array of 1.1"],
    "1.2": {
        key: "object of 1.2"
    },
    "1.1.1": 999,
    "1.2.1": true,
    "1.2.2": function () {
        return "function of 1.2.2";
    },
    "1.3": null,
    "2": 2
}

我想完成以下多维数组:

为了简单地解释我自己:

[
    ["1",
        [
            [
                [
                    "1.1",
                    [
                        "1.1.1"
                    ]
                ]
            ],
            [
                [
                    "1.2",
                    [
                        "1.2.1",
                        "1.2.2"
                    ]
                ],
            ],
            "1.3"
        ]
    ],
    "2"
]

最终数组:

[
    [
        "Text of 1",
        [
            [
                [
                    ["array of 1.1"],
                    [
                        999
                    ]
                ]
            ],
            [
                [
                    {
                        key: "object of 1.2"
                    },
                    [
                        true,
                        function()
                        {
                            return "function of 1.2.2";
                        }
                    ]
                ],
            ],
            null
        ]
    ],
    2
]

请注意,最深的元素不会包装到数组中。

如何在纯香草 js中执行通用递归函数来完成此任务?

主要目标是执行一个console.group()调用树,例如在console.groupEnd()每个树分支的末尾也会调用。如果顶部的对象执行这些控制台调用,那么帮助我完成这个也是一个奖励。

标签: javascriptarraysrecursionconsole.log

解决方案


这是我的解决方案,

var numberedList = { "1": "Text of 1", "1.1": ["array of 1.1"], "1.2": { key: "object of 1.2" }, "1.1.1": 999, "1.2.1": true, "1.2.2": function () { return "function of 1.2.2"; }, "1.3": null, "2": 2 }


function gen(numberedList) {
    let result = Object.keys(numberedList).reduce((res, key) => {
        let indexs = key.split(".");
        let lastindex = indexs.pop()
        indexs.reduce((res, i) => res[i], res)[lastindex] = [key]
        return res
    }, []);

    result.shift(); // Removing first item, Becouse index count from 0;
    return result
}

console.log(gen(numberedList))

您需要创建一个trimer函数来修剪此结果,以删除括号 ([])


推荐阅读