如何将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
相关产品推荐
相关产品推荐

