我创建了一个 ImmutableJS map ,如下所示:
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;
关于javascript - Immutable.js 映射 : Find key from value,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62675842/