skip to Main Content

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


  1. 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.

    Login or Signup to reply.
  2. This is due to a not found entry by the function Array.prototype.find this function returns undefined 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 function find returns undefined.

    Within the following code snippet, you can see additional alternatives.

    const Person = (Object.entries(People).find(([,values])=>values.includes('Amy')) || [])[0]
    
    const People = {    groupA : ['Amy','Beth'],    groupB : ['Ben','Matt'],    groupC : ['Jen','Eli']};
    
    //OR operator
    let Person = (Object.entries(People).find(([,values])=>values.includes('Ele')) || [])[0];
    
    console.log(Person);
    
    //Optional chaining operator (?.)
    Person = Object.entries(People).find(([,values])=>values.includes('Ele'))?.[0];
    
    console.log(Person);
    
    //Nullish coalescing operator
    Person = (Object.entries(People).find(([,values])=>values.includes('Ele')) ?? [])[0];
    
    console.log(Person);
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search