Today I encountered a problem that made me realize I needed to find a better solution.
The issue at hand involves an immutable array of objects.
[
{
id: 0,
value:10
},
{
id: 1,
value:20
},
{
id: 2,
value:20
},
]
I had the task of searching through this array, locating the object with my specific id, and then retrieving a single value from within that object.
This is how I tackled it:
// extract the entire object from the array
const tempObject = immutableArray.toJS().find(elem => (elem.id === myId));
// create a temporary variable to hold the desired value
let tempValue = 0;
// validate the object
if(tempObject !-- undefined){
// store the extracted value
tempValue = tempObject.value;
}
To me, this method seems quite inefficient. Why save the complete object when all I need is one value?
I believe it should be something more streamlined like
const myValue = immutableArray.toJS().find(elem => (elem.id === myId).value);
or even
const myValue = immutableArray.toJS().find(elem => (elem.id === myId)).value;
However, as it turns out, those approaches do not actually work.
Is there a more direct way to access this value without storing the entire object?