2016-06-23 7 views
-4

У меня возникла ошибка, указывающая, что data.forEach не является функцией. Код:Для каждого цикла ---> Для цикла

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. Теперь у меня проблема со следующим 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 создает массив из ключей объекта. Затем вы можете перебирать эти ключи и получать связанное значение. Этот подход будет работать над любыми объектами.

Смежные вопросы