-4

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

Barmar
  • 741,623
  • 53
  • 500
  • 612
Mr.KGK
  • 5
  • 6

2 Answers2

0

forEach works on arrays, not on objects. It seems here that data is an object.

Use this instead.

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 creates an array from the keys of an object. You can then iterate over these keys and fetch the associated value. This approach will work on any objects.

Quentin Roy
  • 7,677
  • 2
  • 32
  • 50
0

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()
        }            
    }
});
Barmar
  • 741,623
  • 53
  • 500
  • 612