I want to check if an array inside an object exists, is not null and is not empty
I need to reference that property in bracket notation.
My object
profile = {
myArray: [1,2,3]
}
And I am checking it like this
const section = "myArray";
if(section in profile && profile[section] && profile[section].length ) { // do something}
I expect this to work but I get an error in this part profile[section].length
that says object is possibly null or undefined
If I do it using dot notation it works right
if('myArray' in profile && profile.myArray && profile.myArray.length ) { // do something}
myArray = [1,2,3]
the = should be a colon.object[...]
notation, it relies onobject
's index signature. Because of that, it can't tell that the property you've checked for truthiness is the same property you're accessing thelength
property of.