[英]Swap key,value inside a node.js collections dictionary
I am using this node.js collection module. 我正在使用此node.js收集模块。 http://www.collectionsjs.com/ http://www.collectionsjs.com/
I would like to swap the key with the value inside a collections dictionary. 我想将键与集合字典中的值交换。
To illustrate, here is the original dictionary. 为了说明这一点,这是原始词典。
"use strict";
var Dict = require("collections/dict");
var Data_type = new Dict(
{
"00": "DATA_0",
"01": "DATA_1",
"02": "DATA_2",
});
After swapping, the new dictionary will look like this; 交换之后,新字典将如下所示;
var Data_type_swapped = new Dict(
{
"DATA_0": "00",
"DATA_1": "01",
"DATA_2": "02",
});
There are no duplicate values in the original dictionary. 原始词典中没有重复的值。
I am using node.js v6. 我正在使用node.js v6。
I am not familiar with the library, but I skimmed the documentation and came up with this: 我不熟悉该库,但是我浏览了文档并提出了以下建议:
let Dict = require('collections/dict');
let d = new Dict({ 'key1': 'value1', 'key2': 'value2' });
d.keys().forEach(key => {
d.set(d.get(key), key);
d.delete(key); // This could cause trouble if your value is the same as your key
});
It iterates through all keys, adds a new entry identified by the value of the current key, sets its value and then deletes the old key 遍历所有键,添加由当前键的值标识的新条目,设置其值,然后删除旧键
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.