清除从列表中返回对象的方法

时间:2018-04-06 01:19:42

标签: javascript reactjs lodash

我目前正在执行此操作以从数组中返回用户对象

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

有更简洁的方法吗?

这是一个reactjs应用程序,所以我可以选择在必要时使用任何花哨的库。我已经在我的包裹中提供了lodash以防万一。

1 个答案:

答案 0 :(得分:3)

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