I have this if else expression filtering elements inside dogs[] courses[] departments[] the first snippet definitely works the way I want but my problem is its not reusable and the way is es5-ish.
1st snippet
if (item == 'dogs') {
item = 'dogs';
return this[`${item}`].filter(item => new RegExp(`^${data}`, 'gi').test(item));
} else if (item == 'courses') {
item = 'courses';
return this[`${item}`].filter(item => new RegExp(`^${data}`, 'gi').test(item));
} else if (item == 'departments') {
item = 'departments';
this.dept = this.deptControl.value;
return this[`${item}`].filter(item => new RegExp(`^${data}`, 'gi').test(item.name));
}
In this snippet I tried my best to shorten the es5-ish code but the deptartments[] does not work, the way I want
2nd snippet
item =
item == 'dogs' ? 'dogs'
: item == 'courses' ? 'courses'
: item == 'departments' ? 'departments' : '';
return this[`${item}`].filter(item => new RegExp(`^${data}`, 'gi').test(item == 'departments' ? item.name : item));
and the department[] in this snippet is likewise doesn't work the way I want
3rd snippet
item =
item == 'dogs' ? 'dogs'
: item == 'courses' ? 'courses'
: item == 'departments' ? 'departments' : '';
// let patch = item == 'departments' ? item.name : item;
let patch = item == 'departments' ? item['name'] : item;
return this[`${item}`].filter(item => new RegExp(`^${data}`, 'gi').test(patch));
Please help me how to fix my issue in the departments[] block, using ternary operator, not the old style if..else
item = item || ""this.deptin the first block.item = item || ""?itemis a string, then getitem.name, and you're filtering just one item ?