teachtyler teachtyler - 2 months ago 16
Javascript Question

return object values with const 1 liner

So here's an example of some code, using an array of objects, for simple arbitrary data.

const function at the bottom to find my flight number represented as


var flights = [{
"id": 1234,
"airline": "Delta",
"depart": "11/23/2016 10:25 AM",
"arrive": "11/23/2016 11:35 AM",
"from": "TPA",
"to": "MEM"
}, {
"id": 4321,
"airline": "AA",
"depart": "11/23/2016 12:25 PM",
"arrive": "11/23/2016 2:35 PM",
"from": "DWF",
"to": "SEA"

var flightNu = 4321;

const flightDetails = (a) =>
a.map(f => (f.id == flightNu) ? f : null )


So my question lies with properly defining this const function

const flightDetails = (a) =>
a.map(f => (f.id == flightNu) ? f : null )

This is returning
[null, Object]

Object is the correct one, with flightNu.
Found it, cool, but let's say I add 100 objects, that'd be 99 nulls returned. That's 99 problems but a Matching Flight Number ain't one. (sorry)

Can someone shed some light on a good way to use this? Maybe I shouldn't be using ternary operator. If I could return the proper
that'd be great.

Preferably without assigning Object to another variable

var MatchingFlight;

const flightDetails = (a) =>
a.map(f => {
if (f.id === flightNu){
MatchingFlight = f;
}) ? MatchingFlight : null //returns Object {} close but meh

This snippet works in the proposed goal sense, but defining MatchingFlight outside of scope doesn't seem right for


You can use filter in JavaScript which returns the elements that match the filter something like this

const flightDetails = (a) => 
a.filter(f => (f.id == flightNu))