Postman中如何通过if条件从响应数组提取指定title对象的索引与id
Postman 条件判断匹配实现代码
你可以通过for循环遍历响应数组,在循环内加if条件匹配title字段实现需求,完整代码如下:
var jsonData = pm.response.json(); // 配置目标匹配title var targetTitle = "Canary"; var schoolIndex = -1; var schoolId = null; // 遍历响应数组 for (var i = 0; i < jsonData.length; i++) { // if条件匹配title字段 if (jsonData[i].title === targetTitle) { schoolIndex = i; schoolId = jsonData[i].id; // 匹配成功后终止循环 break; } } console.log("匹配到的索引:", schoolIndex); pm.collectionVariables.set("school Index", schoolIndex); // 兜底校验,避免未匹配到时报错 if (schoolIndex !== -1) { pm.collectionVariables.set("schoolId", schoolId); } else { console.warn("未找到title为【" + targetTitle + "】的对象"); }
代码说明
- 初始设置索引默认值为-1,和原生findIndex方法未匹配到的返回规则保持一致
- 遍历过程中通过if判断完成title字段的等值匹配,匹配到后立即终止循环,减少不必要的遍历操作
- 增加了未匹配到的兜底逻辑,避免访问不存在的数组下标导致脚本报错
内容的提问来源于stack exchange,提问作者TorvaldLova
相关产品推荐
相关产品推荐

