我当前执行此操作是为了从数组返回用户对象
const userIndex = users.findIndex((user) => { return user.id === source.userId; }); const user = users[userIndex];
有没有更干净的方法?
这是一个reactjs应用程序,因此如果需要,我可以选择使用任何奇特的库。我的包裹里有lodash,以防有用。
使用函数的更干净方法 find :
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; }