Angular管道中如何将字符串参数解析为嵌套对象属性用于过滤?
Solution for Parsing Nested Property Paths in Angular Pipe
Got it, I see the problem here. When you write it.keyName, JavaScript is looking for a property literally named keyName on your it object—not the nested property path you're passing in (like name.value). To fix this, you need a helper function that can take an object and a dot-separated path string, then traverse the object to get the correct value.
Here's how you can modify your pipe:
First, add a helper function inside your pipe class (or as a standalone utility) to resolve nested properties:
private getNestedValue(obj: any, path: string): any { // Split the path into individual keys (e.g., 'name.value' becomes ['name', 'value']) const keys = path.split('.'); // Traverse the object one key at a time return keys.reduce((current, key) => { // If current is undefined/null, stop traversing to avoid errors return current && current[key] !== undefined ? current[key] : ''; }, obj); }
Then update your transform method to use this helper instead of direct property access:
transform(items: any[], searchText: string, keyName: string = ''): any[] { if (!items) { return []; } if (!searchText || !keyName) { return items; } searchText = searchText.toLowerCase(); return items.filter(it => { // Get the nested value using our helper const value = this.getNestedValue(it, keyName); // Convert to string (in case value is a number/boolean) and check for match return value.toString().toLowerCase().includes(searchText); }); }
What this does:
- The
getNestedValuefunction splits your path string into an array of keys, then usesreduceto step through each key in the object. If at any point a key doesn't exist (or the current value isnull/undefined), it returns an empty string to avoid runtime errors. - In the filter, we convert the retrieved value to a string first—this handles cases where your nested value might be a number or boolean instead of a string.
- Now when you pass
keyName="name.value", the code will correctly resolve toit.name.valueinstead of looking for akeyNameproperty.
Edge cases handled:
- If
keyNameis empty, the pipe returns all items (we added a check for!keyNamein the early return). - If a nested property doesn't exist on an item, it treats that value as an empty string, so those items won't match the search (unless the search text is empty).
内容的提问来源于stack exchange,提问作者Sandra Willford
相关产品推荐
相关产品推荐

