2

I have this code

const arr = [{
  id: 1,
  name: 'anything'
}, {
  id: 2,
  name: 'something'
}]

const target = [1]

I want to find whether target has 1 and I want the name property value

I'll do

arr.find(o => target.includes(o.id)).name

but this will break if

arr.find(o => target.includes(o.id)) doesn't have the name property, it break the entire app and throw error.

So how to ensure this from being crashed? I can do this but it's ugly

const somethingValue = arr.find(o => target.includes(o.id)) && arr.find(o => target.includes(o.id)).name

or I have to map to ensure the arr always have name property, I have to do this if the arr is dynamic and the south comes from external party.

Any other way to solve this?

Charles Jr.
  • 117
  • 5

2 Answers2

1

Extract the result from .find into a variable first, and then check to see if that variable is defined:

const foundObject = arr.find(o => target.includes(o.id));
const somethingValue = foundObject ? foundObject.name : null;
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
1

You can use empty object {} and || operator.

(arr.find(o => target.includes(o.id)) || {}).name

If find() will return undefined so the expression will evaluate to {} and try to get name from {} which is undefined

Maheer Ali
  • 35,834
  • 5
  • 42
  • 73