如何从路径(键数组)创建嵌套对象结构?

Tra*_*vis 0 javascript arrays string object javascript-objects

我正在尝试制作一些接受字符串数组的东西,然后构建嵌套对象链,这些对象基本上存储输入数组中的字符串之后的内容。最初,这些链的深度为 2,但我需要能够生成更深的链。

基本上,我需要采用这样的数组:

["test1", "test2", "test3", "test4"]
Run Code Online (Sandbox Code Playgroud)

并将其转换为:

{
    "test1":
    {
        "test2":
        {
            "test3":
            {
                "test4": {}
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

gyr*_*yre 6

这看起来像一份工作Array#reduce

function objectFromPath (path) {
  var result = {}
  
  path.reduce(function (o, k) {
    return (o[k] = {})
  }, result)
  
  return result
}

var path = ["test1", "test2", "test3", "test4"]

console.log(objectFromPath(path))
Run Code Online (Sandbox Code Playgroud)
.as-console-wrapper { min-height: 100%; }
Run Code Online (Sandbox Code Playgroud)

  • 不要以为他会变得比这更好 (3认同)
  • 谢谢你的回答,尤其是编辑我的问题的标题。现在我真的知道我想做的事情叫什么! (2认同)