简体   繁体   English

Typescript - 将 Map 转换为逗号分隔的字符串

[英]Typescript - Converting a Map to a comma separated string

I have a map that I'm converting a specific string format using:我有一个 map 我正在使用以下方法转换特定的字符串格式:

let content = "";
let myMap = new Map().set('a', 1).set('b', 2).set('c', 3);
myMap.forEach((value: string, key: number) => {
   content += `${key}: ${value}, `;
});

However this will leave a comma at the end.但是,这将在末尾留下一个逗号。

Is there some other way?还有其他方法吗? eg to be able to use join ?例如能够使用join

Thanks,谢谢,

This works:这有效:

Object.keys(myMap).map(data => [data, myMap[data]]).map(([k, v]) => `${k}:${v}`).join(', ');

You can convert the map to an array, and then use join after a quick transformation:您可以将 map 转换为数组,然后在快速转换后使用join

 let myMap = new Map().set('a', 1).set('b', 2).set('c', 3); let str = [...myMap].map(([k, v]) => `${k}: ${v}`).join(", "); console.log(str);

Yes, you can use join是的,您可以使用join

let content = []; // array
let myMap = new Map().set('a', 1).set('b', 2).set('c', 3);

myMap.forEach((value, key) => {
   content.push(`${key}: ${value}`); // push all elts into the array
});

content is now an array ["a: 1", "b: 2", "c: 3"] content现在是一个数组["a: 1", "b: 2", "c: 3"]

use join to convert it to a comma separated string使用 join 将其转换为逗号分隔的字符串

content = content.join(); 

desired output "a: 1,b: 2,c: 3"所需 output "a: 1,b: 2,c: 3"

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

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