I have Function that maps out an Array in to Groups and now I want to access the keys and values in the groups
Code to group array with new Map()
reduceArray() {
console.log("this.toDoList", this.toDoList);
const MapArrayIntoGroups = this.toDoList.reduce(
(Map, e) => Map.set(e.ID, [...Map.get(e.ID)||[], e]),
new Map()
);
console.log("MapArrayIntoGroups",MapArrayIntoGroups);
const key = MapArrayIntoGroups.get(); // get Key
console.log("key",key);
const value = MapArrayIntoGroups.get(); // value array
console.log("value",value);
}
Here is the result
I have trying MapArrayIntoGroups.get(value); etc.. with no success. How do I access those keys, values
You can iterate your map with for of:
for (const [key, value] of MapArrayIntoGroups) {
console.log(key)
console.log(value)
}
or forEach:
MapArrayIntoGroups.forEach(function(value, key) {
console.log(key)
console.log(value)
}
Instead of
const key = MapArrayIntoGroups.get(); // get Key
console.log("key",key);
const value = MapArrayIntoGroups.get(); // value array
console.log("value",value);
Do like that to get the value if you know the key
const key = 1496
const value =MapArrayIntoGroups.get(key);
How do I access those keys, values
//utility function to get keys of each entry
const keys = arrays => arrays.map(array=>array[0]);
// keys([...MapArrayIntoGroups]);// try this to get all keys like an array [1496,...]
Thanks @Heretic said in comments that map has Already a method called keys(); Which is self-explanatory get all keys of an map
Array.from(MapArrayIntoGroups.keys());
//or
[...MapArrayIntoGroups.keys()];