TypeScript中数组映射、过滤并获取唯一元素的正确方法及语法纠错
Fixing "Illegal return statement" and Extracting Unique Level Values
First, let's break down why your code snippets were causing issues:
- Second & Third Snippets: After using
map(p => p.Level), you're left with an array of strings (e.g.,["a", "b", "b"]). Trying to accessp.Levelorp.levelon these strings is invalid—strings don't have aLevelproperty! That's why you were seeing errors here. - First Snippet: This one is syntactically valid, but it doesn't handle deduplication. You'd get repeated entries of the same Level value instead of unique ones.
Now, let's implement the correct solution based on your goal: extracting unique Level values (either all unique values from the dataset, or only those matching this.usrInfo.a).
Option 1: Get All Unique Level Values (Sorted)
If you want every distinct Level from the data, sorted alphabetically:
this.myService.myMethod().subscribe( data => { // Extract all Level values first const allLevels = data.map(item => item.Level); // Use a Set to deduplicate, then convert back to array and sort this.levelsList = [...new Set(allLevels)].sort(); } );
Option 2: Get Unique Level Values Matching this.usrInfo.a
If you only want the Level value that matches this.usrInfo.a (ensuring it's added only once, even if it appears multiple times):
this.myService.myMethod().subscribe( data => { // Filter items where Level matches usrInfo.a, extract the Level value const matchingLevels = data .filter(item => item.Level === this.usrInfo.a) .map(item => item.Level); // Deduplicate and sort (though this will only have one unique value if matches exist) this.levelsList = [...new Set(matchingLevels)].sort(); // Alternative (simpler for single-value case): // this.levelsList = data.some(item => item.Level === this.usrInfo.a) ? [this.usrInfo.a] : []; } );
Key Notes:
Setfor Deduplication: Usingnew Set()automatically removes duplicate values from an array—this is the most concise and efficient way to handle uniqueness in modern JavaScript/TypeScript.- Arrow Function Syntax: When using arrow functions without curly braces (
=>), the return is implicit. If you use curly braces, you need an explicitreturn(which you had correctly in your first snippet). - Avoiding Property Errors: Always check what type of data you're working with after
map—if you convert objects to strings, don't try to access object properties on those strings!
内容的提问来源于stack exchange,提问作者haydnD
相关产品推荐
相关产品推荐

