JavaScript Switch表达式如何实现大小写不敏感?GeoJSON属性适配
解决GeoJSON属性键大小写不一致的switch判断问题
我有两个GeoJSON文件,它们的属性键/标签名称相同但大小写不同,分别为feature.properties.STATUS和feature.properties.status。我希望通过同一个switch语句来判断这两个文件的属性值:
function PathStyle(feature) { switch (feature.properties.STATUS) { case "FP": return {color: 'blue'}; case "BR": return {color: 'green'}; // 其他情况... } }
但当前代码仅对大写的STATUS属性值生效。我尝试过多种方式使用.toLowerCase()方法,但都未成功,例如:
function PathStyle(feature) { var str = "feature.properties.STATUS"; var strLC = str.toLowerCase(); console.log(strLC); switch (strLC) { // 其他情况... } }
请问是否有解决该问题的方案?
你的问题核心是之前的尝试操作了字符串字面量而非实际的属性值,导致根本没拿到GeoJSON里的状态数据。下面是两种直接可行的解决方法:
方法一:直接兼容两种属性键
如果确定两个GeoJSON不会同时存在STATUS和status键,直接用逻辑或运算符优先取值:
function PathStyle(feature) { // 优先取大写STATUS,不存在则取小写status const status = feature.properties.STATUS || feature.properties.status; switch (status) { case "FP": return {color: 'blue'}; case "BR": return {color: 'green'}; // 补充其他case default: return {color: 'gray'}; // 定义默认样式 } }
方法二:通用匹配任意大小写的属性键
如果需要兼容更多大小写变体(比如Status),可以遍历属性键找到匹配项:
function PathStyle(feature) { // 遍历属性键,找到忽略大小写后等于"status"的键 const statusKey = Object.keys(feature.properties).find( key => key.toLowerCase() === 'status' ); // 获取属性值,无匹配则设为null const status = statusKey ? feature.properties[statusKey] : null; switch (status) { case "FP": return {color: 'blue'}; case "BR": return {color: 'green'}; // 补充其他case default: return {color: 'gray'}; } }
额外优化:统一属性值的大小写
如果属性值也存在大小写不一致的情况(比如fp、Fp),可以把值转成小写后再判断:
function PathStyle(feature) { const statusKey = Object.keys(feature.properties).find( key => key.toLowerCase() === 'status' ); // 转小写,可选链避免null报错 const status = statusKey ? feature.properties[statusKey].toLowerCase() : null; switch (status) { case "fp": return {color: 'blue'}; case "br": return {color: 'green'}; // 补充其他小写case default: return {color: 'gray'}; } }
内容的提问来源于stack exchange,提问作者DaveF
相关产品推荐
相关产品推荐

