0

I am trying to concatenate words and at same time, remove, null and undefined. Currently still getting error in the image below. How would someone resolve this?

javascript-string-concatenation-behavior-with-null-or-undefined-values

In the picture, one of the properties is saying

TypeError: cannot read property of undefined

Its like it cannot even read the argument in first place, to apply the undefined filters, etc.

get copyFromDescription() {
    if (this.addressId == 0) {
        return 'Select';
    } else { return [this.apn, this.combinedAddress,this.addressType.addressTypeDescription].filter(Boolean).join('') }
}

Data Value Picture

enter image description here

2 Answers 2

1

Use

.filter(val => !!val)

Boolean is a type

and test for addressType being undefined with

this.addressType && this.addressType.addressTypeDescription

get copyFromDescription() {
    if (this.addressId == 0) {
        return 'Select';
    } else { return [this.apn, this.combinedAddress,this.addressType && this.addressType.addressTypeDescription].filter(val => !!val).join('') }
}
Sign up to request clarification or add additional context in comments.

2 Comments

also placed a comment, for some reason in my data model, address Type exists, but did not get into the new object array, strange, I will try this out also
also, addessType is nullable member in my model, so when I initialized the model, without that member, its not even showing, thanks
0

this.addressType is undefined. Therefore it can't get a value when trying to access the addressTypeDescription property.

Boolean is a type and not a test. This seems a bit more logical to me.

get copyFromDescription() {
    if (this.addressId == 0) {
        return 'Select';
    } else { return [this.apn, this.combinedAddress,this.addressType.addressTypeDescription].filter(val => !!val).join('') }
}

but then you will still be stuck with the undefined error which needs to be tested for.

get copyFromDescription() {
    if (this.addressId === 0) 
        return 'Select';
    else if (this.addressType) return [this.apn, this.combinedAddress, this.addressType.addressTypeDescription]
      .filter(val => !!val).join('');
    else return [this.apn, this.combinedAddress] // you cannot use addressType here
      .filter(val => !!val).join('');
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.