Array to get element Shortcut

Hey, folks.

Actually, to get some specific array item, we need define the index or use the Array.prototype.filter to refine the result.

Why not create a shortcut to get this in a more easily way:

// Generic array
const _$ = [
    {
        id: 0, name: 'a'
    },
    {
        id: 1, name: 'b'
    },
    {
        id: 2, name: 'c'
    }
];

// The final variable container
let result;

// Changing the shortcut
result = _$ [id:1].name;    // or
result = _$ [{id:1}].name;  // or
result = _$ [id=1].name;    // or
result = _$ [{id=1}].name;  // or
result = _$ [{ id=4, id=1 }].name; // Multiple elements and ignore non-existent
result = _$ [{ id:1, id:1 }].name; // Override existent temporary element

console.log (result); // Expected 'b'

I'll point out a couple existing, and potential future solutions to this problem, just in case you weren't aware of them.

Instead of using Array.prototype.filter(), you can use Array.prototype.find(), which isn't that bad to use and is pretty powerful:

result = _$.find(x => x.id === 1)?.name

There's also this pattern matching proposal. It currently does not help this situation, but if they made a pattern-match operator (something they're not considering right now to keep things simple, but may consider at a future point), then you would be able to do something like this:

result = _$.find(x => x matches { id: 1 })?.name

Also, note that the following are already valid syntax, and already does something in Javascript (if you execute them, you'll notice they don't give you a syntax error):

result = _$ [{id:1}].name;
result = _$ [id=1].name;
result = _$ [{ id:1, id:1 }].name;
1 Like

Nice, man.
The find command looks like so much useful.

But this is a really bad idea minify a little more to get the element?

I'm sorry - I don't follow what you're asking here. Could you expound?

Make a more easily and intuitive way to get element inside an array to use without any methods or additional implementations like find, filter, _.where, etc, recicling the square brackets.

1 Like

Code is read far more often than it's written; making things more concise is a very tricky balance between improving writability and preserving readability.

3 Likes