Search code examples
javascriptreactjslodash

Cleaner way to return an object from within a list


I am currently doing this to return a user object from an array

const userIndex = users.findIndex((user) => { return user.id === source.userId; });
const user = users[userIndex];

Is there a cleaner way to do this?

This is a reactjs app so I have the option to use any fancy library if necessary. I have lodash in my packages in case that would help.


Solution

  • Cleaner approach using the function find:

    const user = users.find(({id}) => id === source.userId);
    

    Example

    const users = [{
      id: 2,
      name: "Ele"
    }];
    
    const source = {
      userId: 2
    };
    
    const user = users.find(({id}) => id === source.userId);
    
    console.log(user);
    .as-console-wrapper { max-height: 100% !important; top: 0; }