首页 > 解决方案 > 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

但是这种解决方案感觉非常“笨拙”,而且不是很整洁或快速。是否有内置方法或更好的方法来做到这一点?

标签: javascriptimmutable.js

解决方案


您可以使用使用Array.prototype.find的这一行函数:

const getSeatFromPerson = (seatMap, person) => [...seatMap.keys()].find(seat => seatMap.get(seat) === person) || null;

推荐阅读