javascript 用下划线交换字典中的键和值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28427277/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 08:57:55  来源:igfitidea点击:

Swap keys and values in dictionary with underscore

javascriptunderscore.js

提问by user2846569

Lets say we have a dictionary with unique values:

假设我们有一个具有唯一值的字典:

{ a: 1, b: 2 }

and we would like to swap keys and values like:

我们想交换键和值,例如:

{ 1: 'a', 2: 'b' }

how to do it with underscore?

如何用下划线做到这一点?

回答by Alexander T.

In underscore.jsthere is method _.invert

underscore.js有方法 _.invert

console.log(_.invert({ a: 1, b: 2 }))
<script src="//jashkenas.github.io/underscore/underscore-min.js"></script>