简体   繁体   English

无法使用 JS 变量访问带有“:”的 GeoJSON 属性

[英]Unable to access GeoJSON properties with “:” using JS variable

I am currently following the tutorial on Mapbox to build a store locator with a map.我目前正在按照Mapbox 上的教程来构建一个带有 map 的商店定位器。

I'm having problems displaying data from my GeoJSON file that I got from Turbo Overpass.我在显示从 Turbo Overpass 获得的 GeoJSON 文件中的数据时遇到问题。 Example of the GeoJSON being used:使用的 GeoJSON 示例:

"properties": {
    "@id": "node/5750820619",
    "addr:city": "Caissargues",
    "addr:housenumber": "180",
    "addr:postcode": "30132",
    "addr:street": "Avenue de la Vistrenque",
    "description:covid19": "horaires légèrement réduits",
    "name": "Bio Marché",
},

In my Javascript file I can access properties such as name using this code:在我的 Javascript 文件中,我可以使用以下代码访问名称等属性:

var details = listing.appendChild(document.createElement('div'));
details.innerHTML = prop.addr:city;

...but am unable to figure out how to access the addr:city or addr:postcode field as I either get an unexpected identified in vs code or it returns a undefined value in the website. ...但我无法弄清楚如何访问addr:cityaddr:postcode字段,因为我在 vs 代码中发现了一个意外,或者它在网站中返回了一个未定义的值。 I've tried using prop.addr:city;我试过使用prop.addr:city; , prop.addr/':city'/; , prop.addr/':city'/; and other ways proposed on websites.以及网站上提出的其他方式。

If someone could point me in the right direction or propose the solution I would be very grateful.如果有人能指出我正确的方向或提出解决方案,我将不胜感激。 Thanks !谢谢 !

You should access these properties like this:您应该像这样访问这些属性:

details.innerHTML = prop['addr:city'];

This works because in Javascript object properties can always be accessed using these brackets.这是可行的,因为在 Javascript object 中,始终可以使用这些括号访问属性。

For example this:例如这个:

const a = prop.a;

is equal to等于

const a = prop['a'];

However using the last syntax Javascript is a lot more relaxed.但是,使用最后一种语法 Javascript 会轻松很多。 You could even do this:你甚至可以这样做:

const property = prop['some property with lots of spaces'];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM