JavaScript で組み込みの Proxy オブジェクトを使用する方法


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 を使用してクールなアイデアをコメントに投稿してください。