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

如何在response中获取多个ID分别对应的索引

方案实现

你可以把原有函数调整为接收ID数组参数,遍历要查询的ID批量返回匹配结果,示例代码如下:

// 入参兼容单个ID或ID数组传入
function getIndexes(categoryIds) {
    // 统一转成数组处理,兼容旧调用逻辑
    const idsToQuery = Array.isArray(categoryIds) ? categoryIds : [categoryIds];
    // 返回对象格式:key为CategoryID,value为对应索引,匹配失败返回-1,和原有逻辑行为一致
    return idsToQuery.reduce((result, id) => {
        result[id] = response.responseContents.findIndex(obj => obj.CategoryID === id);
        return result;
    }, {});
}

// 调用示例:传入你需要查询的3个ID即可
const targetIds = [2, 7, 12]; // 替换为实际需要查询的CategoryID
const indexMap = getIndexes(targetIds);

// 直接通过ID取对应索引
console.log(indexMap[2]); // 输出ID为2对应的索引
console.log(indexMap[7]); // 输出ID为7对应的索引
console.log(indexMap[12]); // 输出ID为12对应的索引

高频查询优化方案

如果response.responseContents数据量较大、需要多次查询多ID索引,可以提前预生成ID到索引的映射表,避免每次查询都遍历全数组,性能更高:

// 全局仅执行一次生成映射表
const categoryIdToIndex = response.responseContents.reduce((map, item, index) => {
    map[item.CategoryID] = index;
    return map;
}, {});

// 后续任意查询直接取值,时间复杂度O(1)
const index1 = categoryIdToIndex[2];
const index2 = categoryIdToIndex[7];
const index3 = categoryIdToIndex[12];

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 09:15:04