在循环中创建一个深度(水平)对象
我不确定表达这个问题的最佳方式是什么,但基本上我希望创建一个循环来创建如下对象:
var dictionary = {};
var arr = [
["for", "item", "in", "list"],
["if", "condition"]
];
// Insert Magic Loop to yield:
dictionary.for.item.in.list // {} (exists, as well as rest of chain)
dictionary.if.condition // {} (exists, as well as rest of chain)
dictionary.for.item // {}
dictionary.test // undefined
I wasn't sure what the best way to word this question is but basically I'm looking to create a loop that create objects like this:
var dictionary = {};
var arr = [
["for", "item", "in", "list"],
["if", "condition"]
];
// Insert Magic Loop to yield:
dictionary.for.item.in.list // {} (exists, as well as rest of chain)
dictionary.if.condition // {} (exists, as well as rest of chain)
dictionary.for.item // {}
dictionary.test // undefined
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我的脑海中浮现出:
编辑
这是解决方案的一个子集。我写了一个函数,它接受一个数组和一个字典作为参数:
如果你不担心覆盖,你可以去掉循环中的
if
:并且为了更好的可读性:
Off the top of my head:
EDIT
Here is a subset of the solution. I wrote a function that takes in an array and a dictionary as parameters:
If you're not worried about overwriting, you can take out the
if
in the loop:And for better readability:
这将需要一些修改(每个序列从顶部重新启动),但显示了降序向下的总体思路:
快乐编码
This will need some modification (restart at top for each sequence), but shows the general idea of descending-down:
Happy coding