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

遍历SearchResult获取嵌套info属性时返回undefined的问题求助

Troubleshooting the "undefined" Error When Extracting info Properties from SearchResult

Hey there, let’s break down why you’re hitting that undefined error even though you can see the name field in the console! Here are the most likely issues and fixes to get your code working:

1. Not All Entries in SearchResult Have a Valid info Object

The console might show you one complete entry, but it’s common for dynamic data (like API responses) to have incomplete items. Some keys in SearchResult could point to objects that either lack an info property entirely, or their info doesn’t include the name field you’re trying to access.

Fix: Add Defensive Checks

Use optional chaining (?.) to safely access nested properties without throwing errors, and add fallback values with the nullish coalescing operator (??). We’ll also log problematic entries to debug exactly which items are breaking things:

for (let productKey in SearchResult) {
  if (SearchResult.hasOwnProperty(productKey)) {
    const product = SearchResult[productKey];
    
    // Skip entries without a valid info object
    if (!product?.info) {
      console.warn(`Skipping product ${productKey}: No info property found`, product);
      continue;
    }

    products.push({
      name: product.info.name ?? 'Unnamed Product',
      image: product.info.image ?? '',
      url_key: product.info.url_key ?? '',
      productId: product.info.pid ?? '',
    });
  }
}

2. for-in Might Be Traversing Unintended Properties

Even with hasOwnProperty, edge cases (like modified object prototypes) can lead to unexpected keys being looped over. A more reliable approach is to use Object.keys() to target only the own enumerable keys of SearchResult:

Object.keys(SearchResult).forEach(productKey => {
  const product = SearchResult[productKey];
  
  if (product?.info) {
    products.push({
      name: product.info.name ?? 'Unnamed Product',
      image: product.info.image ?? '',
      url_key: product.info.url_key ?? '',
      productId: product.info.pid ?? '',
    });
  } else {
    console.warn(`Product ${productKey} is missing required info`, product);
  }
});

3. Quick Debugging Hack

To pinpoint the exact issue, add a log statement inside your loop to inspect every product entry:

console.log(`Checking product ${productKey}:`, product);

This will show you immediately if any entry has an info object that’s undefined, or if name is actually missing despite what you saw in the console.


内容的提问来源于stack exchange,提问作者godhelpmeimstuck12

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.29 16:42:37