javascript - 使用数组的反向映射
问题描述
我有一组Map
需要同时使用的数据;这是一个例子:
const mapping: Map<string, string> = new Map<string, string>([
['one', '1'],
['two', '2'],
['three', '3'],
['four', '4'],
]);
// I should eliminate this; I want to write it with single-line syntax
const reverseMapping: Map<string, string> = new Map<string, string>([
['1', 'one'],
['2', 'two'],
['3', 'three'],
['4', 'four'],
]);
const data = Array.from(mapping).map(e => e.reverse());
const reverseMap: Map<string, string> = new Map<string, string>([data])
我无法从语法上弄清楚如何做到这一点;我该怎么做?
解决方案
在运行时和编译器中都可以使用的单行器是这样的:
const flipMap = <K, V>(m: Map<K, V>) => new Map(Array.from(m, ([k, v]) => [v, k]));
// const flipMap: <K, V>(m: Map<K, V>) => Map<V, K>
对于您的特定地图,您可以这样做:
const reverseMapping = new Map(Array.from(mapping, ([k, v]) => [v, k]));
// const reverseMapping: Map<string, string>
让我们测试一下:
console.log(mapping); // Map(4) { one → "1", two → "2", three → "3", four → "4" }
console.log(reverseMapping); // { 1 → "one", 2 → "two", 3 → "three", 4 → "four" }
在我看来很好。希望有帮助;祝你好运!
推荐阅读
- sorbet - 是否可以为单个文件生成隐藏定义?
- python - 如何通过bpy.types获取具体的修饰符属性信息?
- android - 我无法在 android studio 中构建任何项目:无法解决
- python - 如何从数据库生日字段和 date.today() 计算确切年龄?
- git - Git cherry-pick 删除非主分支和差异
- excel - 有没有办法使用 VBA 自动填充 Pi DataLink 数据?
- javascript - 异步函数无法识别更新的 var;异步函数在完成前解析
- python - 如何使用 txcouchbase 进行身份验证?
- swift - 使用 PHPhoto Libary 和 alamofire 快速上传图片
- python - 如何使用 Pandas 将第二天日期低于现有日期值