0

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.

2
  • Your code throws an error Uncaught ReferenceError: _ is not defined Commented Jul 23, 2019 at 8:10
  • this is because i use lodash librairy, you can test it here lodash.com/docs/4.17.14 Commented Jul 23, 2019 at 8:27

2 Answers 2

2

You can indeed use .map to get the results you desire:

const parsedCities = data.features
    .map(f => `${f.properties.postcode} ${f.properties.city}`)
    .filter((f, i, a) => a.indexOf(f) === i); 

//["43000 Le Puy-en-Velay", "43000 Espaly-Saint-Marcel"]

You can find the documentation on Array.prototype.map() here.

Sign up to request clarification or add additional context in comments.

3 Comments

Well, I guess, upvoters and the author himself missed OP's remark 'Cities in the result should be unique'
The problem with just this solution is if there are multiples cities with same name it won't be filtered and it will have duplicate in the array. Cities should be unique but not postcode (this is why i used _.uniq function and then verify if it is undefined)
@maxd updated answer with filtering unique items. I don't understand what you mean by cities should be unique but not postcode, does this mean its fine if you have ["Town A - 12345", "Town A - 12344"] or not? Right now it just filters so that the combination of town and postcode is unique.
0

One may use

const src = {"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"};

const uniqueCities = obj => 
  [...new Set(obj.features.map(({properties:{city,citycode}}) => citycode+' '+city))]
 
console.log(uniqueCities(src));
.as-console-wrapper {min-height: 100%}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.