An Interest In:
Web News this Week
- March 21, 2024
- March 20, 2024
- March 19, 2024
- March 18, 2024
- March 17, 2024
- March 16, 2024
- March 15, 2024
December 18, 2021 04:02 pm GMT
Post your cool ideas with
Original Link: https://dev.to/gajananpp/how-to-use-built-in-proxy-object-in-javascript-3kh1
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 arrayconst items = [ { id: '123', name: 'phone' }, { id: '789', name: 'tablet' }, { id: '1011', name: 'laptop' }]// define custom hooksconst handlers = { get: (target, prop) => { return target.find(item => item.name === prop) }}// create proxy objectconst 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'}
More more in depth information check out MDN guide or comment below in case of doubt.
You can play with the above code here :-
// our arrayconst items = [ { id: '123', name: 'phone' }, { id: '789', name: 'tablet' }, { id: '1011', name: 'laptop' }]// define custom hooksconst handlers = { get: (target, prop) => { return target.find(item => item.name === prop) }}// create proxy objectconst 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.
Original Link: https://dev.to/gajananpp/how-to-use-built-in-proxy-object-in-javascript-3kh1
Share this article:
Tweet
View Full Article
Dev To
An online community for sharing and discovering great ideas, having debates, and making friendsMore About this Source Visit Dev To