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
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.
Related
Json Array Object
Through Ajax I will get dynamic data which is not constant or similar data based on query data will change. But I want to display charts so I used chartjs where I need to pass array data. So I tried below code but whenever data changes that code will break.
I cannot paste complete JSON file so after parsing it looks like this
[{"brand":"DUNKIN' DONUTS KEURIG","volume":1.9,"value":571757},{"brand":"MC CAFE","volume":1.1,"value":265096}];
You can use Object.keys and specify the position number to get that value
var valueOne =[];
var valueTwo = [];
jsonData.forEach(function(e){
valueOne.push(e[Object.keys(e)[1]]);
valueTwo.push(e[Object.keys(e)[2]]);
})
It seems like what you're trying to do is conditionally populate an array based the data you are receiving. One solution might be for you to use a variable who's value is based on whether the value or price property exist on the object. For example, in your forEach loop:
const valueOne = [];
jsonData.forEach((e) => {
const val = typeof e.value !== undefined ? e.value : e.average;
valueOne.push(val);
})
In your jsonData.forEach loop you can test existence of element by using something like:
if (e['volume']===undefined) {
valueone.push(e.price);
} else {
valueone.push(e.volume);
}
And similar for valuetwo...
You could create an object with the keys of your first array element, and values corresponding to the arrays you are after:
var data = [{"brand":"DUNKIN' DONUTS KEURIG","volume":1.9,"value":571757},{"brand":"MC CAFE","volume":1.1,"value":265096}];
var splitArrays = Object.keys(data[0]).reduce((o, e) => {
o[e] = data.map(el => el[e]);
return o;
}, {});
// show the whole object
console.log(splitArrays);
// show the individual arrays
console.log("brand");
console.log(splitArrays.brand);
console.log("volume");
console.log(splitArrays.volume);
// etc
I am attempting to pull out individual rows and specific data from the census data using node.js JSON.parse.
const http = require('http');
function printStuff(statesInfo){
const statesPopulations = `${statesInfo} This is all states info`;
console.log(statesPopulations);
}
const request = http.get(`http://api.census.gov/data/2013/acs5?get=NAME,B01001_001E&for=state:*&key=4c2f7253819e5491c78ff2c5ed541fe95943854c`,
response => {
let body = "";
console.log('Status Code:', response.statusCode);
response.on('data', data=> {
body += data.toString();
});
response.on('end', () => {
const statePop = JSON.parse(body);
const statesInfo = JSON.parse(body);
printStuff(statesInfo);
})
});
Using console.log(body) the results show up as...
NAME,B01001_001E,state,Alabama,4799277,01,Alaska,720316,02,Arizona,6479703,04,Arkansas,2933369,05,California,37659181,06,Colorado,51
19329,08,Connecticut,3583561,09,Delaware.......
if I use console.dir(body), the results show up as....
[[NAME][B01001][state]
['Alabama', '4799927', '01'],
[ 'Alaska', '720316', '02' ]] ....
all the way down to Puerto Rico. I am trying to pull specific things out but examples I've been using on Treehouse are set up all nice and neat where you can pull specifically labeled things out using nice things like profile.badges.length, but from what I can tell, none of these things are labelled. I would like to be able to say, pull Virginia's info out of there, or Delaware.
Most likely the examples you are seeing on Treehouse use an object with keys {Alabama: {...}} instead of the array that you get back from census.gov [["Alabama", ...]].
To access California's population you need to get the 6th(index 5 since its 0 based) nested array from the parent. Which looks like this:
get the California array
console.log(statePop[5]); // outputs ["California","37659181","06"]
get the population of California by getting the second item in the California array.
console.log(statePop[5][1]); // outputs "37659181"
If you want a more human readable version(like Treehouse examples) you would have to create an object with keys from the array. You could do this easily with something like lodash or manually like so:
var popByState = {};
// loop through each state and assign values to object keyed by the state name
statePop.forEach(function(stateArr) {
popByState[stateArr[0]] = {population: stateArr[1]};
// Ex stateArr = ["California","37659181","06"]
// stateArr[0] is the name of the state
// stateArr[1] is the population
});
console.log(popByState.California.population) // outputs "37659181";
But then you have to be aware of states that have a space in their name like "New York". You can't use dot notation to access these(console.log(popByState.New York.population)) you have to use brackets console.log(popByState['New York'].population)
I need to create a new object with a generated key and update some other locations, and it should be atomic. Is there some way to do a push with a multi-location update, or do I have to use the old transaction method? This applies for any client platform, but here's an example in JavaScript.
var newData = {};
newData['/users/' + uid + '/last_update'] = Firebase.ServerValue.TIMESTAMP;
newData['/notes/' + /* NEW KEY ??? */] = {
user: uid,
...
};
ref.update(newData);
There are two ways to invoke push in Firebase's JavaScript SDK.
using push(newObject). This will generate a new push id and write the data at the location with that id.
using push(). This will generate a new push id and return a reference to the location with that id. This is a pure client-side operation.
Knowing #2, you can easily get a new push id client-side with:
var newKey = ref.push().key(); // on newer versions ref.push().key;
You can then use this key in your multi-location update.
I'm posting this to save some of future readers' time.
Frank van Puffelen 's answer (many many thanks to this guy!) uses key(), but it should be key.
key() throws TypeError: ref.push(...).key is not a function.
Also note that key gives the last part of a path, so the actual ref that you get it from is irrelevant.
Here is a generic example:
var ref = firebase.database().ref('this/is/irrelevant')
var key1 = ref.push().key // L33TP4THabcabcabcabc
var key2 = ref.push().key // L33TP4THxyzxyzxyzxyz
var updates = {};
updates['path1/'+key1] = 'value1'
updates['path2/'+key2] = 'value2'
ref.update(updates);
that would create this:
{
'path1':
{
'L33TP4THabcabcabcabc': 'value1'
},
'path2':
{
'L33TP4THxyzxyzxyzxyz': 'value2'
}
}
I'm new to firebase, please correct me if I'm wrong.
I am trying to call Javascript's .map() method on a backbone collection that contains a JSON that looks like this:
[
{"from":"houston","to":"austin"},
{"from":"omaha", "to":"kc"}
]
My backbone model looks like this:
var ChoiceModel = Backbone.Model.extend({});
var choiceModel = new ChoiceModel({
a:'from',
z:'omaha'
})
The problem is every JSON document I'm interested in has the Key "from" instead of the city I'm interested in. Below I am trying to filter all the JSONs with the "from" value of "omaha".
var aVar = this.model.get('a');
var zVar = this.model.get('z');
return this.collection.map(function(model){
return {
a: model.get(aVar[zVar])
};
Ideally I would be able to later call variable 'a' it would only return: {"from":"omaha", "to":"kc"}.
I've tried a few variations of the code above to no avail. How can I .map() on JSON values?
so I have a JSON object returned from a webservice. Now I want to:
get a subset which matches a categoryTitle i pass as parameter (this seems to work)
from my filtered resultset I want to get another array of objects (helpsubjects), and for each of this subjects I want to extract the SubjectTitle.
Problem: It seems my Array of HelpSubjects does not exist, but I can't figure out why and hope you could help.
Perhaps this piece of commented code makes it more clear:
$.fn.helpTopicMenu = function (data) {
that = this;
var categoryContent = contents.filter(function (el) {
return el.CategoryTitle == data.categoryTitle;
});
debug('categorys Content: ', categoryContent); //see below
var container = $('#subjectList');
var subjectList = categoryContent.HelpSubjects;
debug('Subjects in Category: ', subjectList); // UNDEFINED?!
$.each(subjectList, function (i, item) {
container.append(
$('<li></li>').html(subjectList[i].SubjectTitle)
);
});
the line debug('categorys Content: ', categoryContent); returns the following object as shown in the picutre (sadly I can't add a picture directly to the post yet, so here's the link): http://i.stack.imgur.com/0kKWx.png
so as I understand it, there IS actually a HelpSubjects-Array, each entry containing a SubjectTitle (in the picture there actually is only one entry, but I need to have the Artikel einfügen as my html.
Would be great if you can help me.
The variable categoryContent set is an array of objects.
Try debugging categoryContent[0].HelpSubjects and see if you can access the property. If so, you can also loop this array if need be.