2016-06-23 189 views
-4

我有一个错误,指出data.forEach不是一个函数。该代码是:对于每个循环---> For循环

function getProperGeojsonFormat(data) { 
    isoGeojson = {"type": "FeatureCollection", "features": []}; 

    console.log("After getProperGeojsonFormat function") 
    console.log(data) 
    console.log("") 

    data.forEach(function(element, index) { 
     isoGeojson.features[index] = {}; 
     isoGeojson.features[index].type = 'Feature'; 
     isoGeojson.features[index].properties = element.properties; 
     isoGeojson.features[index].geometry = {}; 
     isoGeojson.features[index].geometry.coordinates = []; 
     isoGeojson.features[index].geometry.type = 'MultiPolygon'; 

     element.geometry.geometries.forEach(function(el) { 
      isoGeojson.features[index].geometry.coordinates.push(el.coordinates); 
     }); 
    }); 
    $rootScope.$broadcast('isochrones', {isoGeom: isoGeojson}); 



} 

我得到的错误是:

enter image description here

当我控制台日志数据:

When I console log data

+4

这取决于数据是否是一个数组与否。 –

+1

a [mcve]会很棒! –

+1

他们已经帮你 – zerkms

回答

0

data是一个对象。它看起来像要遍历该对象中的features阵列,这样做:

data.features.forEach(function(element, index) { 
    isoGeojson.features[index] = { 
     type: 'Feature', 
     properties: element.properties, 
     geometry: { 
      type: 'MultiPolygon', 
      coordinates: element.coordinates.slice() 
     }    
    } 
}); 
+0

感谢您提示更改data.features.forEach。现在我遇到了下一个问题,每个 –

+0

道歉,但它回到那里 –

+0

不要回答这个问题。我已经回复了原来的问题。 – Barmar

0

forEach阵列上的作品,而不是对象。这里似乎是data是一个对象。

改为使用它。

Object.keys(data).forEach(function(index) { 
    var element = data[index]; 
    isoGeojson.features[index] = {}; 
    isoGeojson.features[index].type = 'Feature'; 
    isoGeojson.features[index].properties = element.properties; 
    isoGeojson.features[index].geometry = {}; 
    isoGeojson.features[index].geometry.coordinates = []; 
    isoGeojson.features[index].geometry.type = 'MultiPolygon'; 

    element.geometry.geometries.forEach(function(el) { 
     isoGeojson.features[index].geometry.coordinates.push(el.coordinates); 
    }); 
}); 

Object.keys从对象的键创建数组。然后您可以迭代这些键并获取关联的值。 这种方法适用于任何物体。