首页 > 解决方案 > 在对象文字中引用javascript中嵌套对象的外层

问题描述

我正在寻找类似于对象文字/初始化程序中的自引用的任务,除了它将用于姨妈/叔叔键的值或父对象的兄弟键。例如:

const obj = {
  parent: {
    child: {
      aunt: /* aunt object */
    }
  },
  aunt: {
    foo: {
      bar: 1
    }
  }
}

这里有一个非常相似的问题Reference nested 'sibling'-property in object literal但不幸的是,这不是我想要的。理想情况下,该解决方案将是可扩展的,并且可能需要处理我想要访问与密钥相关的曾孙对象(如果需要)的情况。谢谢!

标签: javascript

解决方案


在单个对象文字中是不可能的。您必须先定义对象,然后分配给auntkey 。

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)


推荐阅读