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

如何在嵌套对象中搜索指定值并获取对应父级及关联属性值

实现代码

function matchContractIds(jsonData, targetIds) {
  const result = []
  // 遍历最外层实体列表
  jsonData.data.forEach(entity => {
    // 遍历当前实体的所有合同
    entity.contracts.forEach(contract => {
      // 匹配合同ID是否在目标数组中
      if (targetIds.includes(contract.id)) {
        // 存入匹配到的实体名称
        result.push(entity.name)
        // 存入当前合同下的所有项目ID
        contract.projects.forEach(project => {
          result.push(project.id)
        })
      }
    })
  })
  return result
}

// 调用示例
const jsonArr = {
  "data": [{
    "id": 5201,
    "name": "Simple Engineering",
    "contracts": [{
      "id": 461,
      "contract_type_id": 99,
      "contract_status_id": null,
      "pivot": {
          "entity_id": 5201,
          "contract_id": 461
      },
      "projects": [{
          "id": 2785,
          "name": "Something Hydro",
          "pivot": {
              "contract_id": 461,
              "project_id": 2785
          }
       }]
     }]
  }]
}
const ids = [461,452,478,655]
const names = matchContractIds(jsonArr, ids)
// 输出结果为 ["Simple Engineering", 2785],符合需求

可选分组返回版本

如果需要每个匹配结果独立分组,可使用下面的实现,返回结果更易后续处理:

function matchContractIdsGrouped(jsonData, targetIds) {
  const result = []
  jsonData.data.forEach(entity => {
    entity.contracts.forEach(contract => {
      if (targetIds.includes(contract.id)) {
        result.push({
          entityName: entity.name,
          matchedContractId: contract.id,
          projectIds: contract.projects.map(item => item.id)
        })
      }
    })
  })
  return result
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 11:18:02