I’m trying to create a conditional in Typescript that checks if a specific word already exists in the name.
I have this function:
isOrganic() {
for (let i = 0; i < this.items.length; i++) {
if(this.items[i].organic) {
if (' (Organic)' in this.items){
this.items[i].name = this.items[i].name
} else {
this.items[i].name = this.items[i].name.concat(' (Organic)')
}
}
}
}
I want to check if the ‘ (Organic)’ label is already there. If it is, just use the name as is. If it’s not there, add it. Instead, it just keeps adding the label over and over and over…
So:
Apple (Organic) (Organic) (Organic) etc...
I know the problem is in this line:
if (' (Organic)' in this.items)
I just can’t figure out how to set up the conditional.
>Solution :
This will do what you want:
if (this.items[i].name.endsWith(' (Organic)'))
First, you need to fully drill into the item’s name. Then, you need to call a method on the string like contains or endsWith, since the in operator does not work on strings.
Full example:
class Foo {
constructor() {
this.items = []
}
isOrganic() {
for (let i = 0; i < this.items.length; i++) {
if (this.items[i].organic) {
if (this.items[i].name.endsWith(' (Organic)')){
this.items[i].name = this.items[i].name
} else {
this.items[i].name = this.items[i].name.concat(' (Organic)')
}
}
}
}
}
const foo = new Foo()
// test data
foo.items = [
{ name: "A", organic: false },
{ name: "B", organic: true },
{ name: "C (Organic)", organic: true },
]
foo.isOrganic()
console.log(foo.items)
It’s also worth mentioning that this refactored to something much cleaner.
- Use a
for/ofloop to iterate the array of items so that you don’t have tothis.items[i]many times. - Use just one
ifthat will trigger if the item is organic, but does not have the text suffix.
class Foo {
constructor() {
this.items = []
}
isOrganic() {
for (let item of this.items) {
if (item.organic && !item.name.endsWith(' (Organic)')) {
item.name = `${item.name} (Organic)`
}
}
}
}
const foo = new Foo()
// test data
foo.items = [
{ name: "A", organic: false },
{ name: "B", organic: true },
{ name: "C (Organic)", organic: true },
]
foo.isOrganic()
console.log(foo.items)