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

TypeScript中如何优化按条件从JSON数组取值的双重循环?

TypeScript 数组筛选高效实现方案

核心优化思路

将需要匹配的国家编码数组转换为Set结构,利用Set内部哈希表实现的O(1)时间复杂度查询特性,将整体时间复杂度从原实现的O(n*m)(n为待筛选对象数组长度、m为国家编码数组长度)降低到O(n+m),完全避免双层迭代。

注意:不要直接用country.includes(item.codCountry)简化双层循环,该写法本质仍为双层迭代,仅做了语法简化,时间复杂度无变化,数据量较大时性能没有提升。

具体实现代码

基础版(直接输出结果)

// 一次O(m)操作完成Set初始化
const countrySet = new Set(country);

// 仅需一次遍历对象数组,O(n)操作完成筛选
for (const item of objJson) {
  if (countrySet.has(item.codCountry)) {
    console.log(item.desCountry);
  }
}

运行输出和原实现完全一致:

> ARGENTINA
> SPAIN

工程常用版(先收集结果再处理)

如果需要把匹配结果留存后做其他逻辑处理,推荐用这种写法,逻辑更清晰:

const countrySet = new Set(country);
const matchedDesList = objJson
  .filter(item => countrySet.has(item.codCountry))
  .map(item => item.desCountry);

// 按需使用结果
matchedDesList.forEach(console.log);

性能最优TypeScript类型安全版

结合TypeScript类型定义+reduce单次遍历完成筛选和值提取,比filter+map少一次遍历,性能最优,同时类型安全:

// 定义对象类型,提前规避类型错误
interface CountryInfo {
  codCountry: string;
  desCountry: string;
}

const country: string[] = [ 'AR', 'ES'];
const objJson: CountryInfo[] = [
  { codCountry: "AR", desCountry: "ARGENTINA" },
  { codCountry: "CO", desCountry: "COLOMBIA" },
  { codCountry: "ES", desCountry: "SPAIN" }
];

const countrySet = new Set(country);
// reduce单次遍历完成筛选+提取
const result = objJson.reduce<string[]>((acc, curr) => {
  countrySet.has(curr.codCountry) && acc.push(curr.desCountry);
  return acc;
}, []);

console.log(result); // 输出:['ARGENTINA', 'SPAIN']

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 14:54:00