I have this piece of code, however I think it can be written more efficient.
this.selectedDub = this.items.filter(item =>
item.fields.dub_Key.value === value);
this.selectedDubContent = this.selectedDub[0].fields as Dub;
this.selectedDubRendering = this.selectedDub[0] as TypedComponentRendering<Dub>;
Can anyone point me in the right direction?
CodePudding user response:
this.selectedDubRendering = this.items.find(item =>
item.fields.dub_Key.value === value) as TypedComponentRendering<Dub>;
this.selectedDubContent = this.selectedDubRendering?.fields ?? undefined;
You could check out the TypeScript find method: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find
The find() method returns the first element in the provided array that satisfies the provided testing function. If no values satisfy the testing function, undefined is returned.