Home > Software engineering >  Overriding object's default getter operator
Overriding object's default getter operator

Time:08-27

Let's say I have the following object in my JS code:

var myData = {
  "someWeirdPrefix_name": "John Doe",
  "someWeirdPrefix_age": 24,
  ...
}

Is there a way to override the default getter operator (.)? As in, if I write myData.name, I would like to get "John Doe" (thanks to the override). Basically I want to override the method so that I can take the key given, add the weird prefix to the key and then get the value. I know the easy approach would be to just clean my actual data and remove the prefix, but that's not acceptable in my use case. Is this actually possible to do for every property (not just name and age)?

CodePudding user response:

Usually Proxy is used for that

const myData = {
  "someWeirdPrefix_name": "John Doe",
  "someWeirdPrefix_age": 24,
}

const newMyData = new Proxy(myData, {
  get(target, prop, receiver) {
    return target['someWeirdPrefix_'   prop];
  }
})

console.log(newMyData.name)

CodePudding user response:

I suggest you create a proxy over the data object, and on the get handler, you can check if there is a key in myData including the dot notation key, if YES, get the value of that key.

const myData = {
  "someWeirdPrefix_name": "John Doe",
  "someWeirdPrefix_age": 24,
}

const handler = {
   get(target, prop, receiver) {
    return target[Object.keys(target).find(key => key.includes(prop))]
  }
}

const proxy = new Proxy(myData, handler);

console.log(proxy.name)

  • Related