I have to extract specific data from an object. My code works but I wonder if I could improve it by using method like map or filter.
This is for no specific background just for personnel training. Also I am using Lodash library
function extractApi(data) {
var arrayOfTowns = [];
var arrayOfCityCode = [];
var result = [];
//looping throw the expected datas (cities and postcode)
for (var i = 0; i < data.features.length; i++) {
arrayOfCityCode.push(_.toString(data.features[i].properties.postcode));
arrayOfTowns.push(_.toString(data.features[i].properties.city));
//verify unique cities
arrayOfTowns = _.uniq(arrayOfTowns);
//pushing to a new array to have the expected result format
if (arrayOfTowns[i] != undefined && arrayOfCityCode != undefined){
result[i] = arrayOfCityCode[i] + " " + arrayOfTowns[i]
}
}
return result
}
//example with some datas
extractApi( {
"type": "FeatureCollection",
"limit": 20,
"version": "draft",
"licence": "ODbL 1.0",
"attribution": "BAN",
"features": [
{
"type": "Feature",
"properties": {
"importance": 0.6466,
"type": "municipality",
"adm_weight": 4,
"postcode": "43000",
"context": "43, Haute-Loire, Auvergne-Rhône-Alpes (Auvergne)",
"id": "43157",
"population": 18.8,
"x": 769600,
"y": 6438600,
"name": "Le Puy-en-Velay",
"citycode": "43157",
"label": "Le Puy-en-Velay",
"city": "Le Puy-en-Velay",
"score": 0.8769636363636364
},
"geometry": {
"coordinates": [
3.883955,
45.043141
],
"type": "Point"
}
},
{
"type": "Feature",
"properties": {
"importance": 0.0867,
"type": "municipality",
"adm_weight": 1,
"postcode": "43000",
"context": "43, Haute-Loire, Auvergne-Rhône-Alpes (Auvergne)",
"id": "43089",
"population": 3.6,
"x": 767600,
"y": 6438900,
"name": "Espaly-Saint-Marcel",
"citycode": "43089",
"label": "Espaly-Saint-Marcel",
"city": "Espaly-Saint-Marcel",
"score": 0.8260636363636362
},
"geometry": {
"coordinates": [
3.858597,
45.046041
],
"type": "Point"
}
},
],
"query": "43000"
}
)
The goal is to receive all data.features.properties.postcode and data.features.properties.city and push it to an array. For this example the expected result is ["43000 Le Puy-en-Velay", "43000 Espaly-Saint-Marcel"]. Cities in the result should be unique.
Uncaught ReferenceError: _ is not defined