简体   繁体   English

javascript-JSON文件仅在键存在时使用值

[英]javascript - JSON file use a value only if key exists

I'm retrieving an OSM Json from an overpass call, to obtain a list of features that I have to save on a database. 我正在从一个过站调用中检索OSM Json,以获得必须保存在数据库中的功能列表。 Since the data are very different from one another (for example, some of them do have aa 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. 由于数据彼此之间非常不同(例如,其中一些确实有一个称为“ addr:city”的标记,而有些则没有),我想检查一个键是否存在,仅在这种情况下保存相应的值。 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. 我只找到了这个问题,但不是我的情况,因为我不知道一个元素将拥有哪些键,哪些元素没有先验键,并且由于我要处理大量数据,所以我真的无法检查元素一个接一个,当然我不能为每种情况编写一个IF。
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: 这是我用来将数据保存在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 “结果”是json格式的响应

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. 如果您可以从某个地方查询属性名称和标签,甚至可以使它更具动态性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM