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

如何通过子属性值在JavaScript中获取父对象的对应键值对

实现思路

遍历目标对象的items字段下的所有键值对,筛选出子属性id与目标值"b"匹配的条目即可。

具体代码实现

// 定义原始数据
const originData = {
  "someID": "16385421",
  "items": {
    "9836": {
      "id": "a"
    },
    "3648": {
      "id": "b"
    },
    "7738": {
      "id": "c"
    }
  }
}

// 目标子属性值
const targetId = "b"

// 遍历items的键值对查找匹配项
const matchedEntry = Object.entries(originData.items).find(([key, value]) => value.id === targetId)

// 格式化输出结果
if (matchedEntry) {
  const [parentKey, childValue] = matchedEntry
  const result = { [parentKey]: childValue }
  console.log(result) // 输出:{ '3648': { id: 'b' } }
}

代码说明

  • 用Object.entries()方法把items对象转为[键, 值]格式的二维数组,方便遍历匹配
  • 用find()方法匹配到第一个符合条件的条目就终止遍历,性能更高
  • 最终得到的result就是你需要的完整父键+子值的结构

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.23 20:45:05