0

I have the following code:

let urls = new Map<string, any[]>();
urls.set("1", ["param=1", "param2=2", "params3=3"]);
urls.set("2", ["param4=4", "param5=5"]);


function getUrl(): string {
  let _tmp = []; 
  urls.forEach((e) => { 
    _tmp.push(e.join("&"));
  });

  return _tmp.join("&");

}

getUrl();

As result I need to get one complete string: param=1&param2=2&params3=3&param4=4&param5=5

I dont like temprorary variable let _tmp = []; , how to improve this?

Yevhen Horbunkov
  • 14,965
  • 3
  • 20
  • 42

4 Answers4

3

I think this should work for you ;)

let urls = new Map();
urls.set("1", ["param=1", "param2=2", "params3=3"]);
urls.set("2", ["param4=4", "param5=5"]);
let result = Array.from(urls.values()).map(arr => arr.join('&')).join('&');
console.log(result);

You can also achieve this a bit easier using .flat, but then you have to add es2019 to lib section of tsconfig.json, because .falt is not in the official specification. More abut this you can read here: Typescript flatMap, flat, flatten doesn't exist on type any[]

Array.from(urls.values()).flat().join('&')
Krzysztof Kaczyński
  • 4,412
  • 6
  • 28
  • 51
2

Is that what you need?

const urls = new Map()
urls.set("1", ["param=1", "param2=2", "params3=3"])
urls.set("2", ["param4=4", "param5=5"])

const result = [...urls.values()].flat().join('&')
    
console.log(result)
Yevhen Horbunkov
  • 14,965
  • 3
  • 20
  • 42
0

If you really need to use Map of arrays, then following will work:

let urls = new Map<string, any[]>();
urls.set("1", ["param=1", "param2=2", "params3=3"]);
urls.set("2", ["param4=4", "param5=5"]);

function getUrl(): string {
    const sep = '&';
    return Array.from(urls.values())
        .map((params) => {
        return params.join(sep)
    })
    .join(sep);
}

getUrl();
Tymur Taraunekh
  • 219
  • 1
  • 4
-1

You can map the outer values and inside that, you can map the inner values while joining.

let urls = {
  '1': [ 'param=1', 'param2=2', 'params3=3' ],
  '2': [ 'param4=4', 'param5=5' ]
}

function getUrl() {
  return Object.values(urls).map(values => values.join('&')).join('&')
}

console.log(getUrl())

Here is the TypeScript equivalent:

let urls = new Map<string, any[]>();
urls.set("1", ["param=1", "param2=2", "params3=3"]);
urls.set("2", ["param4=4", "param5=5"]);


function getUrl(): string {
    return Array.from(urls.values()).map(values => values.join('&')).join('&')
}

console.log(getUrl())
Mr. Polywhirl
  • 42,981
  • 12
  • 84
  • 132