Typescript - If Conditrional Inside A Map
I am mapping a subset of user data to an object of a refined data set. Inside the map i want to check if a variable is null or undefined, and if yes, then to set this variable to a
Solution 1:
You can express conditions in literal maps, but it is somewhat ugly.
return {
a: 1,
...(some_condition && {
b: 1,
})
};
Solution 2:
As far as i know you can't do that with JUST a map. however you could follow it up with a filter() function:
const newArray = oldArray.map((value, index) => condition ? value : null).filter(v => v);
you basicaly iterate over each item and then return the value or null depending on your condition. Now once you have the map you just filter it by removing the null values from the array.
Notice that the original array is not altered and a new one is returned. thanks for the idea @user8897421 for the idea. i just wanted to turn it into a one liner.
Post a Comment for "Typescript - If Conditrional Inside A Map"