首页 > 解决方案 > 使用 JavaScript 映射嵌套数组

问题描述

我正在尝试使用 .map() 映射嵌套数组,因此我可以在地图中显示和精确定位所有伦敦地下位置。

this.undergroundGeoJson = [
        {
            'type': 'FeatureCollection',

            'crs': { 'type': 'name', 'properties': { 'name': 
            'urn:ogc:def:crs:OGC:1.3:CRS84' } },

            'features': [
                {
                    'type': 'Feature',
                    'geometry': {
                        'type': 'Point',
                        'coordinates': [-0.278126, 51.5025]
                    },
                    'properties': {
                        'name': 'Acton Town'
                    }
                },
                {
                    'type': 'Feature',
                    'geometry': {
                        'type': 'Point',
                        'coordinates': [-0.263033174, 51.50883531]
                    },
                    'properties': {
                        'name': 'Acton Central'
                    }
                },
                {
                    'type': 'Feature',
                    'geometry': {
                        'type': 'Point',
                        'coordinates': [-0.262879534, 51.50856013]
                    },
                    'properties': {
                        'name': 'Acton Central'
                    }
                }
           }
       ]

我需要几何对象中的坐标数组元素。

到目前为止,这是我的代码...

@computed
    get undergroundLatLongs() {
    return this.undergroundGeoJson.map((u) =>
    [u.features.geometry.coordinates[0], 
    u.features.geometry.coordinates[1]]);
}

这是错误日志...

Uncaught TypeError: Cannot read property 'coordinates' of undefined

欢迎任何帮助。

标签: javascriptarraysreactjs

解决方案


features是一个数组,您需要使用它来访问它index

 u.features[i].geometry.coordinates[0]
           ^^^

const undergroundGeoJson =[{'type':'FeatureCollection','crs':{'type':'name','properties':{'name':'urn:ogc:def:crs:OGC:1.3:CRS84'}},'features':[{'type':'Feature','geometry':{'type':'Point','coordinates':[-0.278126,51.5025]},'properties':{'name':'ActonTown'}},{'type':'Feature','geometry':{'type':'Point','coordinates':[-0.263033174,51.50883531]},'properties':{'name':'ActonCentral'}},{'type':'Feature','geometry':{'type':'Point','coordinates':[-0.262879534,51.50856013]},'properties':{'name':'ActonCentral'}}],}];

const ret = undergroundGeoJson.map((u,i) => [
  u.features[i].geometry.coordinates[0],
  u.features[i].geometry.coordinates[1],
]);

console.log(ret);


推荐阅读