首页 > 解决方案 > 如何从数组中的数组中的JSON数组中获取元素

问题描述

我对这个 JSON 有疑问。如何从这里获取坐标?

我尝试使用for(){}下面的代码,但不起作用。

   item {
        "type": "type1",
        "features": [{
                "type": "typeee1",
                "geometry": {
                    "type": "Point",
                    "coordinates": [
                        -19.726330999999998,
                        41.360610000000001
                    ]},
                "properties": {
                    "id_strada": "1433",
                    "nome_strada": "test3",
                } },
            {
                "type": "typeee2",
                "geometry": {
                    "type": "Point",
                    "coordinates": [
                        19.726344999999998,
                        26.36063
                    ] },
                "properties": {
                   id_strada": "13",
                   "nome_strada": "test5",
                } },
            {
                "type": "typeee3",
                "geometry": {
                    "type": "Point",
                    "coordinates": [
                        19.726358999999999,
                        98.36065
                    ] },
                "properties": {
                  id_strada": "14",
                    "nome_strada": "test34",
                } }, {
                "type": "typeee5",
                "geometry": {
                    "type": "Point",
                    "coordinates": [
                        19.726372999999999,
                        55.360669999999999
                    ] },
                "properties": {
                    id_strada": "14335",
                    "nome_strada": "test39",
                } }],
        "last_update": "15-08-2019 15:04:45"
    }

调用 JSON 的函数如下所示。

item: Item[];
        this.ws.getitems().subscribe(
                item => {
                    this.item = item;
                    console.log('this.item.length', this.item.length)
                    for (let i = 0; i < this.item.length; i++) {        
                    }
                }
            );

this.item.length 未定义

我的问题是,如何在这里获取坐标?

你能问我任何想法吗?谢谢!

标签: arraysjsontypescriptnativescript

解决方案


如果您已经在item,坐标在item.geometry.coordinates

如果您提供的 json 是x,您可以在x.features[0].geometry.coordinates.

您可以找到每组坐标:

x.features.forEach(item => {
  let coords = item.geometry.coordinates
  // do something with coords
})

推荐阅读