admin管理员组

文章数量:1323733

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

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

Share Improve this question asked Mar 11, 2020 at 11:28 azdaj zdnakjdnazazdaj zdnakjdnaz 1111 gold badge1 silver badge5 bronze badges
Add a ment  | 

4 Answers 4

Reset to default 5

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)

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)

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

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

本文标签: javascriptConcat all values inside a mapStack Overflow