2017-03-28 117 views
0

我想做一些需要字符串数组的东西,然后构建嵌套对象的链,这些嵌套对象的链基本上存储了输入数组之后的字符串。最初,这些链条的深度为2,但我需要能够生成更高深度的链条。如何从路径(键数组)创建嵌套对象结构?

基本上,我需要一个数组是这样的:

["test1", "test2", "test3", "test4"] 

并将其转换成这样:

{ 
    "test1": 
    { 
     "test2": 
     { 
      "test3": 
      { 
       "test4": {} 
      } 
     } 
    } 
} 

回答

4

这看起来像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))
.as-console-wrapper { min-height: 100%; }

+2

不要以为他会比这更好 – vol7ron

+1

谢谢你的答案,特别是编辑我的问题的标题。现在我真的知道我想要做什么被称为! – Travis