代码之家  ›  专栏  ›  技术社区  ›  Blankman

从列表中返回对象的更简洁的方法

  •  0
  • Blankman  · 技术社区  · 7 年前

    我当前执行此操作是为了从数组返回用户对象

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

    有没有更干净的方法?

    这是一个reactjs应用程序,因此如果需要,我可以选择使用任何奇特的库。我的包裹里有lodash,以防有用。

    1 回复  |  直到 7 年前
        1
  •  3
  •   Ele    7 年前

    使用函数的更干净方法 find :

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

    实例

    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; }