javascript - 在对象文字中引用javascript中嵌套对象的外层
问题描述
我正在寻找类似于对象文字/初始化程序中的自引用的任务,除了它将用于姨妈/叔叔键的值或父对象的兄弟键。例如:
const obj = {
parent: {
child: {
aunt: /* aunt object */
}
},
aunt: {
foo: {
bar: 1
}
}
}
这里有一个非常相似的问题Reference nested 'sibling'-property in object literal但不幸的是,这不是我想要的。理想情况下,该解决方案将是可扩展的,并且可能需要处理我想要访问与密钥相关的曾孙对象(如果需要)的情况。谢谢!
解决方案
在单个对象文字中是不可能的。您必须先定义对象,然后分配给aunt
key 。
const obj = {
parent: {
child: {
}
},
aunt: {
foo: {
bar: 1
}
}
};
obj.parent.child.aunt = obj.aunt;
console.log(obj.parent.child.aunt === obj.aunt)
或者,您可以aunt
预先定义:
const aunt = {
foo: {
bar: 1
}
};
const obj = {
parent: {
child: {
aunt
}
},
aunt
};
console.log(obj.parent.child.aunt === obj.aunt)
推荐阅读
- java - 使用 Android Emulator 从 Eclipse 执行简单的 Appium 脚本时遇到问题,请帮助我确定问题
- flutter - 如何在颤动的计时器应用程序中添加振动
- reactjs - 我想在将api调用传递给redux saga之前拦截它们以检查是否需要刷新Access Token
- c++ - Arduino 代码 - 每分钟执行相同的操作
- java - 尝试显示不在菜单中的片段时,导航抽屉活动项目中的片段重叠
- python - 我如何覆盖 Django Rest Auth 注册?
- python - AttributeError: 'str' 对象没有属性 'ndim' [Python | 喀拉斯]
- python - 在 Python 中使用 AutoReg 函数进行 1 个月预测
- python - Formset 保存除 0 以外的任何小数,即使 formset 已保存且 is_valid() 通过
- java - 如何在 java 中编写(和修复)没有循环的代码