简体   繁体   English

如何循环对象以使顶级键进入吸气剂

[英]how to loop over object to make top level keys into getters

after having discovered that getters will allow me to solve a problem, I'd like to convert all my top level keys into getters but was wondering how I can do this. 在发现吸气剂可以解决我的问题后,我想将所有顶级密钥转换为吸气剂,但想知道如何做到这一点。 I'm leaning towards looping over Object.keys(obj) as a starting point but would appreciate any method: 我倾向于将Object.keys(obj)循环作为起点,但希望使用任何方法:

const obj = {
  parent: {
    child: {
      aunt: this.aunt  // this will be undefined without getters
    }
  },
  aunt: {
    foo: {
      bar: 1
    }
  },...
}

into: 成:

const obj = {
  get parent() {
    return {
      child: {
        aunt: this.aunt
      }
    }
  },
  get aunt(){
    return {
      foo: {
        bar: 1
      }
    }
  },...
}

You could do it nicely with a map function over the object keys and using the defineProperty over a new object: 您可以通过在对象键上使用map函数并在新对象上使用defineProperty来很好地做到这一点:

var obj_getters = {}

Object.keys(obj).map(function(key) {
  Object.defineProperty(obj_getters, key, {
    get: function() { return obj[key] }
  });
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM