You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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 getNestedValue function splits your path string into an array of keys, then uses reduce to step through each key in the object. If at any point a key doesn't exist (or the current value is null/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 to it.name.value instead of looking for a keyName property.

Edge cases handled:

  • If keyName is empty, the pipe returns all items (we added a check for !keyName in 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 03:42:56