Reputation: 176
I have a map returned by performing certain operations on a json data retrieved from a server. The map structure looks like follows when i print the key and values
action = [object Map]
comedy = [object Map]
thriller = [object Map]
And with in a object Map (i.e when i just print the values) they have counts which i expect.
Map {
'spanish' => 3
'english' => 4
}
Map {
'spanish' => 1
'english' => 2
}
I want to convert the nested map inside an array based something like this. is there already existing libraries i can leverage off?
var comedy[] = ['spanish_1', 'english_2']
var action[] =['spanish_3', 'english_4']
Please suggest if this is the ideal way to handle this data as i am finding it difficult to get the data out of the nested map.
Upvotes: 1
Views: 89
Reputation: 23515
Get the items in your map using Map.entries and iterate over it using Array.from to create a new Array
having your desired values.
const myNewArray = Array.from(myMap.entries(), ([
key,
value,
]) => `${key}_${value}`);
EDIT
To get the following result :
{
actions: [
'spanish_3',
...
],
comedy: [
'spanish_3',
...
],
}
I loop on the first map level to feed a new json object that I fill with second level map data.
Array.from(myMap.entries()).reduce((tmp, [
xKey,
xValue,
]) => ({
...tmp,
[xKey]: Array.from(xValue.entries(), ([
yKey,
yValue,
]) => `${yKey}_${yValue}`),
}), {});
To get the following output
[
[
'spanish_3',
...
],
[
'spanish_3',
...
],
...
]
Here I create a 2 dimensional array, that I use along with destructuration (the destructuration will work if you already know the data that's comming).
const [
action,
comedy,
thriller,
] = Array.from(myMap.entries(), ([
xKey,
xValue,
]) => Array.from(xValue.entries(), ([
yKey,
yValue,
]) => `${yKey}_${yValue}`));
There is plenty of use case, depends what info you have and what you want to do with it. Hope all examples will give you enough help to figure your specific use case out. :)
Upvotes: 1
Reputation: 42460
You can convert it to an array and map the data to your desired format:
const map = new Map()
map.set('spanish', 3)
map.set('english', 4)
const result = Array.from(map).map(([key, value]) => `${key}_${value}`)
console.log(result) // ["spanish_3", "english_4"]
Upvotes: 0