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)
这看起来像一份工作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)
归档时间: |
|
查看次数: |
434 次 |
最近记录: |