Search code examples
javascriptarraysimmutable.js

More direct way to return object's specific value from an array in javascript?


So I encountered a situation which left me wanting a different solution.

I have an immutable array of objects.

[
  {
   id: 0,
   value:10
  },
  {
   id: 1,
   value:20
  },
  {
   id: 2,
   value:20
  },
]

and I needed to search through the array, find the object with my id, and then return a single value from within that object.

What I ended up doing:

// pull out the entire object from the array
const tempObject = immutableArray.toJS().find(elem => (elem.id === myId));

// set up a temp var to store the desired value
let tempValue = 0;

// make sure the object is valid
if(tempObject !-- undefined){
   // finally store my value
   tempValue = tempObject.value;
}

This just seems like a waste. Storing an entire object just to get a single value?

I feel like it should be something like

const myValue = immutableArray.toJS().find(elem => (elem.id === myId).value);

or

const myValue = immutableArray.toJS().find(elem => (elem.id === myId)).value;

But obviously that doesn't work.

Is there a more direct way like this to access this value without storing the whole object?


Solution

  • a = [{id: 0, value:10}, {id: 1, value:20}, {id: 2, value:20}];
    console.log((a.find(e => e.id == 1) || {value: 0}).value); // 20
    console.log((a.find(e => e.id == 3) || {value: 0}).value); // 0