There is a node like this
<img src="http://x.JPG" data-latitude="0" data-longitude="0">
In jQuery, I can extract two data attribute like this:
a=node.data("latitude")
b=node.data("longitude")
I was wondering whether there is a way to extract multiple data attributes in one time, like this:
latLng = node.data([latitude, longitude]) // not working
latLng = node.data();
this return object
{
latitude:0,
longitude:0
}
I was wondering whether there is a way to extract multiple data
attributes in one time, like this:
latLng = node.data([latitude, longitude]) // not working
Note, Not certain if expected result is array of values from .node.data() ?
var data = $.map($("img").data(), function(value) {
return value
});
console.log(data);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
<img src="http:././.x.JPG" data-latitude="0" data-longitude="0">
DEMO
var latLng = $('img').data();
$.each(latLng,function(index,value){
alert(value);
});
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'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.
I have some text that I receive from the user:
var text = ['Hello', 'World']; // this is the product of string.split(',')
I need to convert it into an array like this one:
var argument = [['Hello'], ['World']];
I need the input in this format so I can send multiple values to the db.
How can I do this elegantly?
I can't think of anything more elegant for this than map:
E.g.:
var argument = originalString.split(",").map(function(entry) {
return [entry];
});
Or if you've enabled ES6 on your NodeJS installation:
var argument = originalString.split(",").map((entry) => [entry]);
I have the following code to extract values from a JSON response. What I am trying to do is store the data in a similar way to how you would with an associative array in php. Apologies for the code being inefficient. The array comments written down are how I would like it to look in the object.
$.each(responseData, function(k1,v1){
if(k1 == "0"){
$.each(v1, function(k2,v2){
$.each(v2, function(k3, v3){
if(k3 == "val"){
//store in object here
//Array1 = array("time"=>k2, "iVal"=>v3)
console.log(k3 + v3 + k2);
}else{
//Array2 = array("time"=>k2, "aVal"=>v3)
console.log(k3 + v3 + k2);
}
});
});
}
});
So all the information is there but I am not sure how to store each instance for the values in an object. I did try store it like this:
//obj created outside
obj1.date = k2;
obj2.iVal = v3;
But doing this clearly overwrote every time, and only kept the last instance so I am wondering how can I do it so that all values will be stored?
Edit: Added input and output desired.
Input
{"0":{"18.00":{"iVal":85.27,"aVal":0.24},"19.00":{"iVal":85.27,"aVal":0.36},"20.00":{"iVal":0,"aVal":0}}, "success":true}
Desired output
array1 = {"time":"18.00", "iVal":85.27},{"time":"19.00", "iVal":85.27},{"time":"20.00", "iVal":0}
array2 = {"time":"18.00", "aVal":0.24},{"time":"19.00", "aVal":0.36},{"time":"20.00", "aVal":0}
try this :
var g1=[];
var g2=[];
for ( a in o[0])
{
g1.push({time:a , iVal:o[0][a]['iVal']})
g2.push({time:a , aVal:o[0][a]['aVal']})
}
http://jsbin.com/qividoti/3/edit
a json response can be converted back to a js object literal by calling JSON.parse(jsonString) inside the success callback of your ajax call.
from then on there is no need for iterating over that object since you navigate it like any other js object which is can be done in two ways either
the js way -> dot notation
var obj = JSON.parse(jsonStirng);
var value = obj.value;
or like a php array
var value = obj["value"];
I'm trying to do something very simple with javascript but can't quite get my head around it. I'm not sure what format I should be passing the var address as.
$(function() {
$('.latlng').each(function(){
var address = $(this).html();
getMap(address);
});
});
function getMap(address) {
var map = new google.maps.Map(mapDiv, {
center: new google.maps.LatLng(address),
...
});
}
I'm getting an error when I pass the JQuery ref to normal javascript: TypeError: 'undefined' is not an object (evaluating 'a.position=b'). Any help appreciated.
If I read this correctly and you posted this code correctly, you pass a non-existing object lasting to getMap(), while you want to pass the address object. What happens if you correct this?
jQuery instances are just normal javascript objects like all others, so there should not be a problem.
You're passing the variable latLng to getMap, but its value isn't set. Your ready function at the top should look like this:
$(function() {
$('.latlng').each(function(){
var address = $(this).html();
getMap(this);
});
});
Or, if you're trying to pass the address variable you set, make your ready function look like this:
$(function() {
$('.latlng').each(function(){
var address = $(this).html();
getMap(address);
});
});
Your issue has nothing to do with jquery or javascript.
You are passing the wrong data into the LatLng method.
You need to pass in two parameters to the LatLng method:
...
var mapDiv = $('#mapDiv')[0], // also make sure the div is a regular dom node
lat = 7.1011123,
lng = 4.6667566;
function getMap(address) {
var map = new google.maps.Map(mapDiv, {
center: new google.maps.LatLng( lat, lng ), // you must pass in two parameters
...
});
}
If you are trying to get your LatLng coords from a text div then you need to convert your strings into floats.
Supposing the following html is what you use:
<ul>
<li class="latlng">7.4142335,3.1296874</li>
<li class="latlng">8.4135039,-5.1256828</li>
<li class="latlng">-14.4101158,-5.2810335</li>
</ul>
Then this would be the function running getMap() for every .latlng list item:
$('.latlng').each(function( i ){
var address = $(this).text();
address = address.split(','); // convert your text into an array
// send in your lat and lng strings parsed as floats
getMap(
parseFloat( address[0] ),
parseFloat( address[1] )
);
});