You need to enable JavaScript to run this app. 嵌套JSON调用find报非函数错误?如何按domain检索返回匹配子对象
优惠活动
大模型
产品
解决方案
定价
更多

嵌套JSON调用find报非函数错误?如何按domain检索返回匹配子对象

报错核心原因
  • find() 是 JavaScript 数组原型链上的内置方法,仅支持在数组类型的数据上调用
  • 你当前使用的 sites 是普通嵌套 JSON 对象,不属于数组类型,本身不存在 find 方法,因此调用时直接抛出 sites.find is not a function 错误
嵌套结构域名检索实现

你给出的站点结构是不定层级的嵌套对象:部分站点节点下还会挂载子站点条目(比如 dx.com 节点下嵌套了GearBest的站点数据),无法通过写死层级的方式遍历检索,需要用递归逐层遍历的方式实现,匹配规则和你之前数组版本的逻辑完全对齐:只要传入的待匹配域名包含节点自身的 domain 值,就返回对应完整站点子对象。

完整实现代码

// 递归遍历嵌套对象,按域名匹配站点
function findSiteByDomain(source, matchDomain) {
  // 提取当前层级所有节点值做遍历
  const currentNodes = Object.values(source);

  for (const node of currentNodes) {
    // 跳过非对象类型的无效节点
    if (typeof node !== 'object' || node === null) continue;

    // 命中匹配规则,直接返回当前站点对象
    if (node.domain && matchDomain.includes(node.domain)) {
      return node;
    }

    // 当前节点未命中,递归检索其嵌套的子节点
    const childMatched = findSiteByDomain(node, matchDomain);
    if (childMatched) return childMatched;
  }

  // 全层级检索无匹配时返回null
  return null;
}

// 调用示例
const targetDomain = "aliexpress.com";
const foundSite = findSiteByDomain(sites, targetDomain);
// 返回结果:
// {
//   "id": 6115,
//   "name": "Aliexpress WW",
//   "site_url": "https://aliexpress.com/",
//   "domain": "aliexpress.com"
// }

实现说明

  • 适配任意深度的嵌套结构,不需要根据站点的层级关系调整代码
  • 匹配逻辑和你之前数组版本完全一致,不会改变原有域名匹配的判定规则
  • 找到第一个匹配的站点后会立即终止遍历,避免无效性能消耗

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.11.05 21:24:06