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

如何用JavaScript根据兄弟元素值获取对应JSON对象的id值

问题描述

给定如下JSON数据:

{
    "count": 4,
    "checks": 
    [   {
            "id": "8299393",
            "name": "NEW_CUSTOMER",
            "statusCode": "495"
        },
        {
            "id": "4949449",
            "name": "EXISTING_CUSTOMER",
            "statusCode": "497"
        }
        // 更多元素在此
    ]
}

由于checks数组内的元素顺序不固定,无法通过索引(比如res.checks[0])定位元素,请问如何用JavaScript获取name值为EXISTING_CUSTOMER对应的id值(即4949449)?

当前尝试的代码无法正常工作:

// 通过API请求获取数据并解析为JSON
const res = await response.json();

// 获取name为'EXISTING_CUSTOMER'对应的id值
const existingCustId = res.checks.name["EXISTING_CUSTOMER"].id; // 无效代码
解决方案

方法1:使用Array.find()(推荐)

find()方法会返回数组中第一个满足条件的元素,刚好匹配需求:

const res = await response.json();
// 找到name匹配的对象
const existingCust = res.checks.find(item => item.name === 'EXISTING_CUSTOMER');
// 提取id,同时处理找不到匹配项的情况
const existingCustId = existingCust ? existingCust.id : null;

方法2:使用Array.filter()(适用于多匹配场景)

如果数组中可能存在多个name为EXISTING_CUSTOMER的元素,用filter()获取所有匹配项后再取第一个:

const res = await response.json();
const existingCusts = res.checks.filter(item => item.name === 'EXISTING_CUSTOMER');
// 取第一个匹配的id,无匹配则返回null
const existingCustId = existingCusts.length > 0 ? existingCusts[0].id : null;

方法3:传统循环遍历(兼容旧环境)

如果需要兼容不支持ES6数组方法的老浏览器,可以用普通循环:

const res = await response.json();
let existingCustId = null;
for (let i = 0; i < res.checks.length; i++) {
  if (res.checks[i].name === 'EXISTING_CUSTOMER') {
    existingCustId = res.checks[i].id;
    break; // 找到后立即退出循环,提升效率
  }
}
原代码无效原因

res.checks是数组而非对象,没有name属性,自然无法通过res.checks.name["EXISTING_CUSTOMER"]定位元素。必须先遍历数组找到目标对象,再提取其id值。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 02:31:31