azdaj zdnakjdnaz
azdaj zdnakjdnaz

Reputation: 111

Concat all values inside a map

I've got a constant result like this :

result: Map<string, string[]>

When I do a console.log(result) the output is :

Map {
 'toto' => [ 'a-1', 'a-2' ],
 'tata' => [ 'b-1', 'b-2' ],
 'titi' => [ 'c-1', 'c-2' ],
}

What I want to have, it's a constant globalResult with all values like this:

const globalResult = [ 'a-1', 'a-2','b-1','b-2','c-1','c-2' ]

How can I do this ?

Thanks

Upvotes: 2

Views: 2151

Answers (4)

Nina Scholz
Nina Scholz

Reputation: 386624

You could get the values of the properties and flat the arrays.

const 
    object = { toto: ['a-1', 'a-2'], tata: ['b-1', 'b-2'], titi: ['c-1', 'c-2'] },
    array = Object.values(object).flat();

console.log(array);

Upvotes: 2

Sumedh Chakravorty
Sumedh Chakravorty

Reputation: 385

You can use Array.from to covert map values into a flat array

const map = new Map();

map.set('a',11)
map.set('b',22)
map.set('c',33)

const array = Array.from(map.values())
console.log(array)

Upvotes: 3

PrakashT
PrakashT

Reputation: 901

Use forEach function.

  const obj = {
     'toto' : [ 'a-1', 'a-2' ],
     'tata' : [ 'b-1', 'b-2' ],
     'titi' : [ 'c-1', 'c-2' ],
    }

    const arr = [];
    Object.values(obj).forEach(value=>arr.push(...value));
    console.log(arr);

Upvotes: 1

palaѕн
palaѕн

Reputation: 73906

You can get map values into an array and then use flat() method on it like:

const myMap = new Map().set('toto', ['a-1', 'a-2']).set('tata', ['b-1', 'b-2'])
const arr = [...myMap.values()].flat()

console.log(arr)

Upvotes: 5

Related Questions