Title says it all. I’m building out some complex functionality right now, and previously I was returning an array. I don’t want to change the return type since there’s a lot of code written against this already, but users are asking for a way to get items from the array based on the name property of the item without having to filter the returned array themselves.
I’m also shying away from converting it into a key/value object using the name property because the most common use case is to loop over the array.
Below is a code snippet of what I am doing. Essentially instead of returning array
I return arrayProxy
so they can use the syntax array["name=Name Of Something"]
to get the item with that name, with a fallback for default behavior of course.
Is this a bad use of Proxy, or is there a better/different way I should be doing this? Something feels janky about it, but I can’t find anything wrong with it per se.
Looking for input from someone with more experience in this area than I have just to get kind of a “lgtm” or “gtfo” on this idea.
const itemArray = [
{
name: "Bob",
value: 99
},
{
name: "Fu",
value: 101
},
{
name: "Bar",
value: 404
}
]
const itemArrayProxy = new Proxy( itemArray, {
get: ( target, prop, receiver ) => {
// If we are getting an item by name instead of index
if ( String(prop).match(/name=/) ){
// Get just the name to match
const name = String(prop).split("=")[1];
// Filter out all items that don't match the name
const results = receiver.filter( item => item.name === name );
// Return the results, or undefined
return results.length && results.length === 1
? results[0]
: results.length
? results
: undefined
}
// Default get functionality fallback
return Reflect.get( target, prop, receiver );
}
})
console.log( itemArrayProxy["name=Fu"] ) // Gets the object with name = "Fu"