DEV Community

Cover image for Using a Proxy for smart destructuring
Eckehard
Eckehard

Posted on

5 1

Using a Proxy for smart destructuring

The Proxy object enables you to create a proxy for another object... (MDN)

Ok, we understand: Proxies are one of the more exotic language features of Javascript, that are seemingly not so easy to explain. But they enable a clever and sometimes handy design pattern I want to introduce here.

Using smart destructuring

Simply spoken, a proxy can change the behavoir of an object: proxy functions can be invoked if properties are set or read, which is often used to change or limit values. But we can also introduce a completely new behavoir. This is used in the following code:

const extract = (arg) => new Proxy({}, {
    get: (obj, prop) => {
         let ret = arg[prop]
         delete ar[prop]
         return ret
    }
})
let ar = { a: 1, b: 2, c: 3, d: 4 }

let { a, b } = extract(ar) // extract a and b

console.log(a) // => 1
console.log(b) // => 2
console.log(ar) // => {c: 3, d: 4}
Enter fullscreen mode Exit fullscreen mode

The example above gets a and b from the array ar using destructuring, but it not only reads a and b, but removes them from the object. How can we use this? Here is an example that packs all parameters into an array and unpacks them inside the function again:



let a = 1,
    b = 2,
    c = 3,
    d = 4

let myarr = {
    a,
    b,
    c,
    d
}

function test(ar) {
    var {
        a,
        b
    } = split(ar)

    console.log(a) // => 1
    console.log(b) // => 2
    console.log(ar) // => {c: 3, d: 4}
}

test(myarr)
Enter fullscreen mode Exit fullscreen mode

Using a proxy for destructuring is a clever code pattern that can be used for different purposes. As you get the property names of the left side, you can do a lot of crazy stuff like auto-generating functions names from the object keys.

Sentry blog image

How I fixed 20 seconds of lag for every user in just 20 minutes.

Our AI agent was running 10-20 seconds slower than it should, impacting both our own developers and our early adopters. See how I used Sentry Profiling to fix it in record time.

Read more

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay