JavaScript で組み込みの Proxy オブジェクトを使用する方法
4091 ワード
Proxy
オブジェクトを使用すると、既存のオブジェクトにカスタムの get、set、delete 動作を追加できます.Proxy
を使用する便利な方法の 1 つを次に示します.これにより、インデックスではなく値で json 配列をクエリできます.
// 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'}
詳細については、MDN guide を確認するか、疑問がある場合は以下にコメントしてください.
ここで上記のコードで遊ぶことができます:-
//配列
const 項目 = [
{
ID: '123',
名前:「電話」
}、
{
id: '789',
名前:「タブレット」
}、
{
id: '1011',
名前:「ラップトップ」
}
]
//カスタムフックを定義
const ハンドラ = {
取得: (ターゲット、小道具) => {
return target.find(item => item.name === prop)
}
}
//プロキシ オブジェクトを作成します
const customItems = new Proxy(アイテム、ハンドラー)
//インデックスの代わりに名前で配列にアクセスできるようになりました 😀
console.log(customItems['ラップトップ'])
//ログ => { id: '1011', name: 'laptop'}
💡 Proxy を使用してクールなアイデアをコメントに投稿してください。
Reference
この問題について(JavaScript で組み込みの Proxy オブジェクトを使用する方法), 我々は、より多くの情報をここで見つけました https://dev.to/gajananpp/how-to-use-built-in-proxy-object-in-javascript-3kh1テキストは自由に共有またはコピーできます。ただし、このドキュメントのURLは参考URLとして残しておいてください。
Collection and Share based on the CC Protocol