javascript - Immutable.js Map:从值中查找键
问题描述
我有一个像这样创建的 ImmutableJS 地图:
const seatMap = Immutable.fromJS({
seatOne: 'Martin',
seatTwo: 'Emelie',
seatThree: 'Erik'
});
我想知道某个特定的人正在使用哪个座位。可以假设这些值是唯一的。
到目前为止,我提出了一种解决方案:
const getSeatFromPerson = (seatMap, person) => {
const [ ...keys ] = seatMap.keys();
for (let i = 0; i < keys.length; i++ {
if (seatMap.get(keys[i]) === person) {
return keys[i];
}
}
return null;
};
console.log(getSeatFromPerson(seatMap, 'Martin')); // Should be "seatOne"
console.log(getSeatFromPerson(seatMap, 'Erik')); // Should be "seatThree"
console.log(getSeatFromPerson(seatMap, 'Christopher')); // Should be null
但是这种解决方案感觉非常“笨拙”,而且不是很整洁或快速。是否有内置方法或更好的方法来做到这一点?
解决方案
您可以使用使用Array.prototype.find的这一行函数:
const getSeatFromPerson = (seatMap, person) => [...seatMap.keys()].find(seat => seatMap.get(seat) === person) || null;
推荐阅读
- c# - 斯坦福 NLP 代码中的异常
- json - 使用 Javascript 导入 JSON,如何跳过延迟异常?
- vuejs2 - 页面上带有可选动态路由的链接总是没有 vuejs 中的参数
- reactjs - 编写动作时 redux 出现意外错误
- js-xlsx - webpack后如何减小xlsx大小
- django - 使用 apache 2.4 部署 django 项目不能公开工作
- c# - 从嵌套列表视图中获取单击行的索引 - UWP
- javascript - 在 React 中使用动态键设置状态
- python - 在 x 轴上绘制日期失败并扩展到子图
- sql-server-2008 - 机器人框架 - 连接到 MS SQL 数据库 - 登录错误