17

Hi I was wondering if anyone knew how to get an array out of a proxy's target value in JavaScript. I have something like this :

Proxy :
  [[target]] : Array // the array I need to extract
  [[handler]] : Object 
  [[IsRevoked]] : false
user3840170
  • 26,597
  • 4
  • 30
  • 62
Jip Helsen
  • 1,034
  • 4
  • 15
  • 30

3 Answers3

10

Just take that original object and parse it to and from JSON and get yourself a clean object!

item = JSON.parse(JSON.stringify(item))
Pinch
  • 4,009
  • 8
  • 40
  • 60
6

If all you have is a reference to the proxy, there is no way (by default) for you to get the proxy's target. A specific proxy could provide a way (via one of its trap handlers, probably), but there is none by default.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • 1
    Also, subjectively: Presumably your code has been given a proxy on the array instead of the array itself *for a reason*. The code providing the proxy would appear not to want your code to have direct access to the array, so trying to get that direct access (even if you can) is probably asking for trouble. – T.J. Crowder Mar 28 '22 at 09:29
  • You're probably right I'll look into the code providing me the proxy. I'll approve your answer as soon as possible. – Jip Helsen Mar 28 '22 at 09:33
3

As an addition, you may get a copy of the target by spreading if the handler maps everything accordingly. But you can not get the original [[target]] object.

const proxy = new Proxy([1, 2, 3], {
  get(target, prop, receiver) {
    return target[prop];
  }
});

console.log([...proxy]);
Hao Wu
  • 17,573
  • 6
  • 28
  • 60
  • Note that extra care needs to be taken in the `get` method to ensure that when `Symbol.iterator` is accessed by `...` it doesn't accidentally overwrite `Array.prototype[Symbol.iterator]`. (but I guess that is what you mean by the handler mapping everything accordingly?) – Nick Parsons Mar 28 '22 at 09:48