使用键数组检查嵌套对象
我有一个数组(目标),其中包含一系列嵌套对象的键。在稍后为其设置值之前,我需要确保那里有一个对象。这段代码是有效的,但仅限于我不厌其烦地重复它。
如何对数组中的 n 个键执行此操作,而不重复此切换到无穷大?
for t, index in target
switch i
when 1
if object[target[0]] is undefined
object[target[0]] = {}
when 2
if object[target[0]][target[1]] is undefined
object[target[0]][target[1]] = {}
when 3
if object[target[0]][target[1]][target[2]] is undefined
object[target[0]][target[1]][target[2]] = {}
when 4
if object[target[0]][target[1]][target[2]][target[3]] is undefined
object[target[0]][target[1]][target[2]][target[3]] = {}
when 5
if object[target[0]][target[1]][target[2]][target[3]][target[4]] is undefined
object[target[0]][target[1]][target[2]][target[3]][target[4]] = {}
when 6
if object[target[0]][target[1]][target[2]][target[3]][target[4]][target[5]] is undefined
object[target[0]][target[1]][target[2]][target[3]][target[4]][target[5]] = {}
I've got an array (target) with keys to a series of nested objects. I need to make sure there is a object there before I set a value to it later on. This code is working but only so far as I can be bothered to repeat it.
How can I do this for n number of keys in the array without repeating this switch to infinity?
for t, index in target
switch i
when 1
if object[target[0]] is undefined
object[target[0]] = {}
when 2
if object[target[0]][target[1]] is undefined
object[target[0]][target[1]] = {}
when 3
if object[target[0]][target[1]][target[2]] is undefined
object[target[0]][target[1]][target[2]] = {}
when 4
if object[target[0]][target[1]][target[2]][target[3]] is undefined
object[target[0]][target[1]][target[2]][target[3]] = {}
when 5
if object[target[0]][target[1]][target[2]][target[3]][target[4]] is undefined
object[target[0]][target[1]][target[2]][target[3]][target[4]] = {}
when 6
if object[target[0]][target[1]][target[2]][target[3]][target[4]][target[5]] is undefined
object[target[0]][target[1]][target[2]][target[3]][target[4]][target[5]] = {}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
警告来自我脑海中未经测试的代码。但这应该可以...
或者一个更 JavaScripty 的版本:
第一个更清晰,第二个更优雅(恕我直言)(并且不会用
current
污染作用域)。caveat untested code from the top of my head. But this should work...
Or a more javascripty version:
The first one is more legible, the second more elegant imho (and does not pollute the scope with
current
).