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

如何将jQuery $.each方法转换为TypeScript for循环处理GeoJSON属性?

解决方案

首先明确:GeoJSON结构中features的properties是键值对对象,并非数组,因此不能使用基于索引的for循环(如for(let j=0; j<...length; j++))遍历,需采用对象键值对的遍历方式。

方法1:for...in循环(兼容传统场景)

直接遍历对象的键,同时通过hasOwnProperty确保仅遍历自身属性:

const heads: string[] = [];
const items: any[][] = [];

// 收集第一个feature的所有属性名到heads
const firstFeatureProps = data.features[0].properties;
for (const key in firstFeatureProps) {
  if (Object.prototype.hasOwnProperty.call(firstFeatureProps, key)) {
    heads.push(key);
  }
}

// 遍历每个feature处理properties
for (let i = 0; i < data.features.length; i++) {
  const currentProps = data.features[i].properties;
  // 初始化当前feature对应的子数组
  items[i] = items[i] || [];
  // 按heads的顺序取值,保证输出顺序一致
  for (const key of heads) {
    const val = currentProps[key];
    items[i].push(val);
  }
}

方法2:Object.entries()(现代简洁写法)

利用ES6+的Object.entries()直接获取键值对数组,简化遍历逻辑:

const heads: string[] = [];
const items: any[][] = [];

// 收集属性名
const firstPropsEntries = Object.entries(data.features[0].properties);
heads.push(...firstPropsEntries.map(([key]) => key));

// 批量处理每个feature的属性值
for (let i = 0; i < data.features.length; i++) {
  const propsEntries = Object.entries(data.features[i].properties);
  items[i] = propsEntries.map(([_, val]) => val);
}

核心注意点

  • 原代码中data.features[i].properties.length会返回undefined,因为对象没有length属性,这是导致循环失效的根本原因。
  • 若需保证所有feature的属性值顺序与heads完全一致,建议按heads的键列表取值,而非直接遍历当前feature的属性(避免对象属性顺序差异问题)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 06:01:44