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

如何利用路径变量提取JSON值并批量获取所有组织ID?

动态路径提取JSON值及批量获取数组元素

一、通过动态路径获取单个值

你可以利用Array.prototype.reduce实现一个通用函数,遍历路径数组逐步深入JSON对象,最终拿到目标值:

const myJson = {
  "id": "someID",
  "organizations": [
    {
      "id": "organizationId",
      "name": "organizationName"
    },
    {
      "id": "anotherOrgId",
      "name": "anotherOrgName"
    }
  ] 
};

var pathOfKey = ["organizations","0","id"];

// 通用路径取值函数
function getValueByPath(obj, path) {
  return path.reduce((current, key) => {
    // 用可选链避免路径不存在时报错,直接返回undefined
    return current?.[key];
  }, obj);
}

// 获取单个组织ID
const singleOrgId = getValueByPath(myJson, pathOfKey);
console.log(singleOrgId); // 输出:organizationId

函数逻辑:以原始JSON对象为初始值,依次遍历路径数组中的每个键,逐步深入对象层级,中途遇到不存在的路径则返回undefined。

二、获取数组中所有组织ID

如果需要批量提取organizations数组里所有元素的id,直接用Array.prototype.map遍历数组即可:

// 批量提取所有组织ID
const allOrgIds = myJson.organizations.map(orgItem => orgItem.id);
console.log(allOrgIds); // 输出:["organizationId", "anotherOrgId"]

如果要结合动态路径的思路(比如数组的键名也需要从变量获取),可以先通过路径拿到目标数组,再遍历提取目标键:

const arrayPath = ["organizations"];
const targetKey = "id";

// 先获取目标数组
const targetArray = getValueByPath(myJson, arrayPath);
// 确保是数组后再批量取值
const allOrgIdsDynamic = Array.isArray(targetArray) ? targetArray.map(item => item[targetKey]) : [];
console.log(allOrgIdsDynamic); // 输出同上

内容的提问来源于stack exchange,提问作者g.b.techne

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 09:35:13