I have an object with keys
const People = {
groupA : ['Amy','Beth'],
groupB : ['Ben','Matt'],
groupC : ['Jen','Eli'],
};
Now I am declaring a varieable where I will pass the values dynamical. for example
const Person = Object.entries(People).find(([,values])=>values.includes('Amy'))[0]
console.log(Person) //output 'groupA'
But when In pass something thats not in the object, its throwing an undefined error. I was not able to understand where to put the if condition.
const Person1 = Object.entries(People).find(([,values])=>values.includes('Brad'))[0]
console.log(Person1) // output should be undefined
I tried putting if conditions but was not able to handle both scenerios.
2
Answers
Try using the Nullish Coalescing Operator, this way you can returns. Default value if it is undefined, you would put this in the return statement after the ‘=>’
Or after the entire Object.entries statement in the variable depending on what is actually returning undefined.
This is due to a not found entry by the function
Array.prototype.find
this function returnsundefined
when no element satisfies the handler condition.An alternative is using the OR (
||
) operator as follows, this approach will return an empty array when the functionfind
returnsundefined
.Within the following code snippet, you can see additional alternatives.