Mr.KGK Mr.KGK - 5 months ago 11
Javascript Question

For Each loop ---> For loop

I am having a error that states that data.forEach is not a function. The code is:

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});



}


The error I am getting is:

enter image description here

When I console log data:

When I console log data

Answer

data is an object. It looks like you want to loop over the features array within that object, so do:

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