mercredi 15 juillet 2020

Can Javascript object key name be retrieved using reflection? [closed]

Given the object:

const product = {
  food: true,
  clothes: false
}

is there a way to programmatically get the name of some key without using Object.keys or similar methods. Something like product.food.getKeyName() which would return a string 'food'. I find that I often have to add object key names to some constants object like:

const products = {
  food: 'food',
  clothes: 'clothes'
}

which is my primary motivation to figure out a programmatic solution.

Here's an example use case. I want to run over all keys of an object and have different behavior for each key:

Object.keys(product).map(key => {
  if (key === 'food') {
    // do something specific for food
  }
})

but I don't want to write string literals like 'food'

Thanks to @Enijar's tip using Javascript Proxy API can do the trick. So for example for the aforementioned product object this is how to get the key name:

const proxyProduct = new Proxy(product, {
    get: function(_, property) {
        return property
    }
})
console.log(proxyProduct.food) // logs 'food'




Aucun commentaire:

Enregistrer un commentaire