0

I'm retrieving an OSM Json from an overpass call, to obtain a list of features that I have to save on a database. Since the data are very different from one another (for example, some of them do have a a tag called "addr:city", and some of them not), I would like to check if a key exists, and only in that case save the corresponding value. I've found only this question but it's not my case, since I do not know a priori which keys one element will have and which not, and since I'm working with a great load of data, I really can't check the elements one by one and of course I can't write an IF for each case.
Is there a way to solve this? I was thinking something about "if key has null value, ignore it", while looping over the elements, but I don't know if something like that exists

EDIT:

This is my query:

https://overpass-api.de/api/interpreter?data=[out:json][timeout:25];(node[~%22^(tourism|historic)$%22~%22.%22](44.12419,%2012.21259,%2044.15727,%2012.27696);way[~%22^(tourism|historic)$%22~%22.%22](44.12419,%2012.21259,%2044.15727,%2012.27696););out%20center; 

and this is the code I'm using to save the data on firebase:

results.elements.forEach(e=>{


  var ref = firebase.database().ref('/point_of_interest/');
  var key = firebase.database().ref().child('point_of_interest').push().key;   
  var updates = {};
  var data = {
    città: e.tags["addr:city"],
    tipologia: e.tags["amenity"],
    indirizzo: e.tags["addr:street"],
    nome: e.tags["name"],
    lat: e.lat,
    lon: e.lon

  }      
  updates['/point_of_interest/'+key] = data;      
  firebase.database().ref().update(updates);      
}) 

"results" is the response in json format

Usr
  • 2,628
  • 10
  • 51
  • 91

1 Answers1

2

You could use something like that:

    var attrs = ["addr:city", "amenity", "addr:street", "name"];
    var labels = ["città", "tipologia", "indirizzo", "nome"]
    var data = { };

    attrs.forEach((a, i) => {
       if (e.tags[a]) { data[labels[i]] = e.tags[a]; }
    });

You could even make this more dynamic, if you can query the attribute names and labels from somewhere.

Crappy
  • 441
  • 3
  • 7
  • Thank you, this is very useful. Since I have a specific structure to have on firebase (that is the one you specified in "labels"), I could use this to insert a string like "undefined" or "not present" in the fields that I don't have, so that everytime I get the data from firebase, I can check the situation and behave accordingly. – Usr Nov 24 '17 at 11:32