2

I have a map that I'm converting a specific string format using:

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? e.g. to be able to use join?

Thanks,

4
  • can you add expected output ??? Commented Nov 13, 2019 at 7:22
  • You can add condition i:e if the index(key) is equal to myMap.length - 1 then don't append comma. Commented Nov 13, 2019 at 7:22
  • 4
    Well, e.g. [...myMap].map(([k, v]) => `${k}: ${v}`).join(", "); works. Commented Nov 13, 2019 at 7:22
  • 1
    @ASDFGerte please post that as an answer Commented Nov 13, 2019 at 7:25

3 Answers 3

2

This works:

Object.keys(myMap).map(data => [data, myMap[data]]).map(([k, v]) => `${k}:${v}`).join(', ');
Sign up to request clarification or add additional context in comments.

Comments

1

You can convert the map to an array, and then use join after a quick transformation:

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);

Comments

0

Yes, you can use 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"]

use join to convert it to a comma separated string

content = content.join(); 

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.