Is it possible to filter null values from a map?
const myMap = new Map<string, string|undefined>([
['id1', 'value1'],
['id2', null],
['id3', 'value3'],
['id4', null],
]);
I would like my map with id1 and id4 only because the other ids have null values.
Thanks
CodePudding user response:
You can convert to array, filter and create a map again:
const myMap = new Map([
['id1', 'value1'],
['id2', null],
['id3', 'value3'],
['id4', null],
]);
const res = new Map(Array.from(myMap).filter(val => val[1]))
CodePudding user response:
You can use .filter()
:
const myMapFiltered = new Map([...myMap].filter(([key, value]) => value));
Or if you want to filter in place:
for (let k of myMap.keys()) {
if (!myMap.get(k))
myMap.delete(k);
}