繁体   English   中英

Typescript将字符串转换为Map

[英]Typescript convert string to Map

我有以下字符串(称为currentExecution.variables):

{executionid=0c3246fb37e65e3368c8c4f30000016ab593bec244daa8df, timeout=10000}

并且我需要将其转换为Map,以便可以处理条目,但是这样做很难。 我尝试按照此答案将其转换为键值对对。 首先,我将=替换为:并将{或}替换为空格,然后根据答案将其拆分:

newString.split(/,(?=[^,]+:)/).map(s => s.split(': '));

但是我没有得到正确的结果,而且没有地图我也陷入困境。 缺少了什么? 还是有更好/更快的方法来做到这一点?

您可以执行以下操作

  1. 从字符串的开头和结尾删除{}字符。 如果内部发生任何情况,请不要使用replace
  2. 将结果分为形成键值对的每个离散块。
  3. 将其拆分为实际的键和值
  4. 结果可以很容易地转换为Map,因为构造函数采用一个数组,其中每个项目都是一个包含两个项目的数组,并将其转换为map,其中第一个项目为键,第二个为值:

 let string = "{executionid=0c3246fb37e65e3368c8c4f30000016ab593bec244daa8df, timeout=10000}"; let keyValuePairs = string.slice(1, -1) //remove first and last character .split(/\\s*,\\s*/) //split with optional spaces around the comma .map(chunk => chunk.split("=")); //split key=value const map = new Map(keyValuePairs); console.log(map.get("executionid")); console.log(map.get("timeout")); 

您也可以不使用正则表达式,但是您必须了解基本概念,首先沿, s分割,然后沿= s分割:

 var data = "{executionid=0c3246fb37e65e3368c8c4f30000016ab593bec244daa8df, timeout=10000}"; var pairs = data.substring(1, data.length - 1).split(", "); // step 1, split using commas var obj = pairs.reduce(function(acc, cur) { var pair = cur.split("="); // step 2, split using = acc[pair[0].trim()] = pair[1].trim(); return acc; }, {}); console.log(obj); 

您可以在此正则表达式所示的捕获组中捕获键和值对。

基于此,您可以继续进行操作,并将其价值减少到地图中。

 const currentExecutionVariable = "{executionid=0c3246fb37e65e3368c8c4f30000016ab593bec244daa8df, timeout=10000}"; const pattern = /([A-Za-z0-9]+)\\=([A-Za-z0-9]+)/g; const matches = currentExecutionVariable.match(pattern); const currentExecutionMap = matches.reduce((acc, curr) => { const [key, value] = curr.split('='); if (!acc.has(key)) { acc.set(key, value); } return acc; }, new Map()); for (const [key, value] of currentExecutionMap.entries()) { console.log (`${key}: ${value}`); } 


更新资料

使用捕获的组:

 const currentExecutionVariable = "{executionid=0c3246fb37e65e3368c8c4f30000016ab593bec244daa8df, timeout=10000}"; const pattern = /([A-Za-z0-9]+)\\=([A-Za-z0-9]+)/g; let currentExecutionMap = new Map(); let capturedGroup; while ((capturedGroup = pattern.exec(currentExecutionVariable))) { // 1st captured group is the key of the map const key = capturedGroup[1]; // 2nd captured group is the value of the map const value = capturedGroup[2]; if (!currentExecutionMap.has(key)) { currentExecutionMap.set(key, value); } } for (const [key, value] of currentExecutionMap.entries()) { console.log(`${key}: ${value}`); } 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM