Skip to content
Advertisement

Using map on a key/value hash treats it like a string

When I do

const pFile = {'a': "b", 'c': 'd'};

var bigExplanation = `
lots of text here
${Object.keys(pFile).map(key => `${key}: ${pFile[key]}`)}
more text here
`;

console.log(bigExplanation);

I get

lots of text here
a: b,c: d
more text here

where I was hoping for

lots of text here
a: b
c: d
more text here

https://jsfiddle.net/ebvo23ks/

Question

Can anyone figure out what I am doing wrong?

Advertisement

Answer

You’ll need to add a newline (rn) after each map() iteration.

Use join() on the map() result;

const pFile = {'a': "b", 'c': 'd'};

var bigExplanation = `
lots of text here
${Object.keys(pFile).map(key => `${key}: ${pFile[key]}`).join("rn")}
more text here
`;

console.log(bigExplanation);

Result;

lots of text here
a: b
c: d
more text here

Edit; the source of the , was due your trying to ‘insert’ a object into a string, for example;

const pFile = {'a': "b", 'c': 'd'};

var bigExplanation = Object.keys(pFile).map(key => `${key}: ${pFile[key]}`);
console.log(typeof bigExplanation);

const string = '---' + bigExplanation + '----';
console.log(string);

Here you can see that (typeof bigExplanation) is an javascript Object, when adding to a string, the , appear between each entry.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement