DEV Community 👩‍💻👨‍💻

Cover image for How to use built-in Proxy object in javascript
Gajanan Patil
Gajanan Patil

Posted on • Updated on

How to use built-in Proxy object in javascript

Proxy object allows you to add custom get, set, delete behaviour on your existing object.

Here is one useful way of using Proxy, which will allow us to query json array with value rather than index.


// our array
const items = [
    {
        id: '123',
        name: 'phone'
    },
    {
        id: '789',
        name: 'tablet'
    },
    {
        id: '1011',
        name: 'laptop'
    }
]

// define custom hooks
const handlers = {
    get: (target, prop) => {
        return target.find(item => item.name === prop)
    }
}

// create proxy object
const customItems = new Proxy(items, handlers)

// now you can access our array with name instead of index 😀
console.log(customItems['laptop'])  
// logs => { id: '1011', name: 'laptop'}
Enter fullscreen mode Exit fullscreen mode

For more in depth information check out MDN guide or comment below in case of doubt.

You can play with the above code here :-

// our array const items = [ { id: '123', name: 'phone' }, { id: '789', name: 'tablet' }, { id: '1011', name: 'laptop' } ] // define custom hooks const handlers = { get: (target, prop) => { return target.find(item => item.name === prop) } } // create proxy object const customItems = new Proxy(items, handlers) // now you can access our array with name instead of index 😀 console.log(customItems['laptop']) // logs => { id: '1011', name: 'laptop'}

💡 Post your cool ideas with Proxy in comments.

Top comments (1)

Collapse
 
crestiancik profile image
Crestiancik • Edited on

Wow, I didn't even know you could do that in Javascript. I mean, the built-in proxy object in javascript makes it way easier sometimes. I mean, you don't have to install a specific proxy for a particular region for your particular software. You already have it from the beginning. But, here I have a couple of new questions. Can I use any proxy I want, or should I get a specific proxy that fits Javascript? I've been using the froxy.com proxies, and I like them very much, so I wouldn't like to use any others.

Regex for lazy developers

regex for lazy devs

You know who you are. Sorry for the callout 😆