I'm looking for an elegant solution to this the following:
In many places of my code, I need to find an object that matches an id in an array of objects and then return a property on that object. The referenced id may or may not exist in the array.
The shortest solution I have come up with is the following:
(wanting to get the title of an item if the item exists, otherwise return none)
arrayofObjects = [ { id: 'a3ff3d', title: 'Tesla', color: 'Red' }, { id: 'r43wesd', title: 'AMC', color: 'Rust' }]
wantedObject = { queryTitle: 'Desired Car', id: 'a3ff3d' }
let wantedProperty = arrayOfObjects.some( e => e.id === wantedObject.id) ? arrayOfObjects.find(e => e.id === wantedObject.id).title : 'None Found'
However, this is neither elegant or as efficient as it should be. I'd prefer for it to be a one liner instead of a function.
for
loop thanArray.prototype
methods.(array.find(…) || {}).title
for
loops.