concatenate string from JSON - javascript

I would like to pull the longitudes and latitudes from an ESRI geometry and concatenate them in to a long string (to be used in an API call).
I am struggling with how to accomplish this
The ESRI documentation for geometry (geometry specs) shows the structure of the object but my API call needs the latitude/longitudes in the following format:
long1,lat1,long2,lat2,long3,lat3 ... long1, lat1
All I have to do is process the long/lats a little bit. Making a very simple example from the ESRI documentation
MyTest = {
"rings": [
[
[-97.06138, 32.837],
[-97.06133, 32.836],
[-97.06124, 32.834],
[-97.06127, 32.832],
[-97.06138, 32.837]
]
],
"spatialReference": {
"wkid": 4326
}
};
alert(JSON.stringify(MyTest.rings[0]));
Will give me the rings (the Longitudes/Latitudes) (notice the first long/lat is repeated as the last long/lat)
I cannot seem to figure out how to strip off the [ and ] to create a string with just the longitudes and latitudes. For instance:
myTest2 = MyTest.rings[0]; // get the longitudes and latitudes
myTest3 = JSON.stringify(myTest2);
myTest4 = myTest3.replace("[","");
alert(JSON.stringify(myTest2));
alert(JSON.stringify(myTest4));
The replace will strip off one of the brackets but I cannot get it to do a global replace like this post stack javascript replace because my programming environment is all within ColdFusion and I need the quotes around the pattern.
Can someone point out my error please ? Thanks !

You may try this (Example) using join():
MyTest = { "rings": [...] };
var str = MyTest.rings.join();
Result (in str) would be:
-97.06138,32.837,-97.06133,32.836,-97.06124,32.834,-97.06127,32.832,-97.06138,32.837

You have an object, use it - don't play with the stringified version.
var coords = MyTest.rings[0];
var list = [];
for ( var i = 0; i < coords.length; ++i )
{
list.push(coords[i][0]);
list.push(coords[i][1]);
}
var str = list.join(',');
// str is now "-97.06138,32.837,-97.06133...(etc.)"

DEMO: http://jsfiddle.net/gunderjt/B5wsK/2/
MyTest.rings[0].join()
and join with no parameters delineates with commas automatically

These are absolute basics, but you don't need to replace anything. [] is just an JavaScript array and not a string.
MyTest.rings.map(function (r) { return r.join(','); }).join(',');
// "-97.06138,32.837,-97.06133,32.836,-97.06124,32.834,-97.06127,32.832,-97.06138,32.837"
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/join

Related

Having Issues with handling Python dictionaries in Javascript flask templates

So I am building a web application using flask that can track mutiple vehicles and provide updates. The python script helps gather all the data and puts them in a dictionary.
I am sending this dictionary over to the index.html with the javascript code within the HTML that initializes a map and places markers based on the coordinates received from python.
The issue I am having is this dictionary is not being parsed properly in js and as a result I get no data.
Right now I have the {{truck_dict}} placeholder to hold the dict object from python in the html.
PS. I am not the best at JS so dont judge XD
#Python Code
return render_template('pages/index.html', trucks = truck.driver_locator(truck.locations()))
#Even when I jsonify/json.dump the variable in the trucks object, nothing happens
#JS Code
var truck_dict = {{trucks | tojson}}
var i;
for (var key in truck_dict){
var value = truck_dict[key];
var geojson = {
type: 'FeatureCollection',
features: [{
type: 'Feature',
geometry: {
type: 'Point',
coordinates: value
},
properties: {
title: 'Mapbox',
description: '1303'
}
}]
};
SAMPLE OUTPUT of the python generated dict
{'1301': [43.1220307, -78.9352247], '1302': [42.3107737, -77.2519131], '1304': [40.3809016, -74.5665863], '1305': [40.2453049, -74.5707928], '1303': [39.6435448, -75.9325289]}
Here is the output:
var truck_dict = {'1301': [43.1220307, -78.9352247], '1302': [42.3107737, -77.2519131], '1304': [40.3809016, -74.5665863], '1305': [40.2453049, -74.5707928], '1303': [39.6435448, -75.9325289]};
for (var i in truck_dict) {
console.log(i, truck_dict[i]);
}
output:
1301 [43.1220307, -78.9352247]
1302 [42.3107737, -77.2519131]
1303 [39.6435448, -75.9325289]
1304 [40.3809016, -74.5665863]
1305 [40.2453049, -74.5707928]
So, you need to log truck_dict, like:
var truck_dict = {{trucks | tojson}};
console.log(trucks);
console.log(truck_dict);
You're trying to index a dictionary.Using truck_dict[I] doesn't work here because your indices are not numbers (not possible in js anyway).
You need to access dictionary elements with their keys (ex. truck_dict['1301'] or truck_dict.1301) NOT indexes. If you want to iterate over each key (which you can use to reference the value mapped to that key), use:
for(var key in truck_dict) {
var value = truck_dict[key];
// do what you need with value and key here
}

Printing JSON Data into innerHTML getting undefined - [object]

Hi guys Im trying to print a list of scores saved within a database, ive got the data as JSON data (see below)
I am trying to print all each object within the "Scores" array using the following code
function showScores() {
var ourRequest = new XMLHttpRequest();
var x, i = "";
ourRequest.open('GET', '/allScores');
ourRequest.onload = function() {
var ourData = JSON.parse(ourRequest.responseText);
for (i in ourData.scores) {
x += ourData.scores[i] + "<br>";
}
document.getElementById("scoresList").innerHTML = x;
};
ourRequest.send();
}
However it is printing out the following
Any help with this is greatly appreciated, thanks guys
This line tries to append a raw object to your HTML string:
x += ourData.scores[i]
Javascript can’t magically parse this into HTML for you, so it just outputs [object Object].
You need to build a string from the individual parts of this object and print that instead. For example:
Note that you should not use for ... in with an array
ourData.scores.forEach(function (score) {
x += `<p>[H] ${score.Home_Team} <b>${score.Home_Score}</b> - <b>${score.Away_Score}</b> ${score.Away_Team} [A]</p>`;
});
Which would output something like this for each score:
[H] Arsenal 2 - 2 Newcastle [A]
Be sure to set x = "" before the loop otherwise the string will still start with undefined.
In case you’re interested: there are more succinct ways of writing this loop. Using Array.map() for instance:
let x = ourData.scores.map(score => {
return `<p>[H] ${score.Home_Team} <b>${score.Home_Score}</b> - <b>${score.Away_Score}</b> ${score.Away_Team} [A]</p>`;
}).join();
This expression does not require initialization of x beforehand.
you can create the elements as string and you can join the entire array and assign it to the innerHTML, as shown below.
You can change the structure, here for example i had made to ul , li you can create table or whatever format.
Note if you want to just append it, since the object you can't directly append it using JSON.stringify which will convert your object into string.
I hope this will solve your issue. Please let me know if any other issue you are facing.
var jsonObj = {scores: [{"Away_Score": 2, "Away_Team": "Newcastle", "Home_Score": 2, "Home_Team": "Arsenal"}, {"Away_Score": 2, "Away_Team": "Napoli", "Home_Score": 4, "Home_Team": "Liverpool"}]}
var html = jsonObj.scores.map(o => {
return `<ul><li>${o.Away_Team}</li><li>${o.Away_Score}</li><li>${o.Home_Team}</li><li>${o.Home_Score}</li></ul>`
})
document.getElementById("todaysData").innerHTML = html.join("")
<div id="todaysData">
</div>

Javascript map CSV string to JSON array

this one baffles me and I'm not even sure I'm searching the correct keywords for possible explanations.
I am sending an RPC to a remote server. The response I get is just a comma-delimited string with values (no keys) like so:
val1,val2,val3,val4,val5,val6,val7,val8,val9
When I receive this response I need to map these values through JS to keys (hard-coded, I designate) and generate a JSON array like this:
{
"response": {
"mykey1" : "val1",
"mykey2" : "val2",
"mykey3" : "val3",
"mykey4" : "val4",
"mykey5" : "val5",
"mykey6" : "val6",
"mykey7" : "val7",
"mykey8" : "val8",
"mykey9" : "val9"
}
}
Can anybody nudge me in the right direction...sample code or tutorials that are close to what I am looking for? This is a for middleware script that gets called when server receives the response.
This is my first post here, been looking a long time learning and applying in Obj-C and as I am learning Swift, but JS is new to me. I apologize in advance if I am breaking any protocols by asking for help without posting my feeble attempts at figuring this out...
You can split the response on comma, which will give you an array.
Since both arrays (keys and vals) are the same length, you can loop over either and create your array of objects that way. See below
var response = 'val1,val2,val3,val4,val5';
var keys = [
'key1', 'key2', 'key3', 'key4', 'key5'
];
var dict = [];
var vals = response.split(',');
vals.forEach(function(val, i) {
dict[keys[i]] = val;
});
console.log(dict);
Read my comment, then check this out:
var result = 'val1,val2,val3,val4,val5,val6,val7,val8,val9';
// real question should be why result is not JSON already
var resArray = result.split(',');
console.log(resArray[0]); // first result
console.log(resArray[1]); // second result

Using a string as GPS coordinates

I am using javascript and I have GPS coordinates in the form of a string and I am trying to put those into the google.maps.LatLng(59.327383, 18.06747) format but am having trouble deciding how to do it. I have a variable:
GPSlocation = "(37.700421688980136, -81.84535319999998)"
and I need it to go into that google.maps.LatLng(num, num) format. How can I put this string in there?
Thanks!
You can use standard string operations to extract the values:
var GPSlocation = "(37.700421688980136, -81.84535319999998)";
var LatLng = GPSlocation.replace("(", "").replace(")", "").split(", ")
var Lat = parseFloat(LatLng[0]);
var Lng = parseFloat(LatLng[1]);
google.maps.LatLng(Lat, Lng)
You can create an Array from it (using JSON.parse), and then use apply to 'feed' the coordinates to the method:
GPSlocation = JSON.parse( "(37.700421688980136, -81.84535319999998)"
.replace(/^\(/,'[')
.replace(/\)$/,']')
);
google.maps.LatLng.apply(null,GPSlocation);
Alternatively you can replace the brackets and use split to create an Array, and call the method LatLng the regular way. This method requires an extra conversion to Number of the Array values.
GPSlocation = "(37.700421688980136, -81.84535319999998)"
.replace(/^\(|\)$/,'')
.split(',');
google.maps.LatLng(+GPSlocation[0],+GPSlocation[1]);
To retrieve an Array of coordinates from the string, you could also use:
GPSlocation = ''.slice.call('(37.700421688980136, -81.84535319999998)',
1,this.length-1)
.split(',')
.map(function(a){return +a;});
google.maps.LatLng(GPSlocation[0],GPSlocation[1]);

javascript multiline dict declaration

I'm having an issue. I want to have a static dict
var myDict={"aaa":true,"aab":false,"aac":false,"aad":true, [...] };
There are a lot of entries, and I want to have an easy access to all of them in case I need to change their value. Because of this, I don't like the single-line declaration.
As an alternative, I did manage to do the following, since multi-line text is allowed in Javascript:
var dict = {};
var loadDict = function() {
text = "aaa,true\n\
aab,false\n\
aac,false\n\
aad,true\n\[...]";
var words = text.split( "\n" );
for ( var i = 0; i < words.length; i++ ) {
var pair = words[i].split(",");
dict[ pair[0].trim() ] = pair[1].trim();
}
}
Is there a better/more elegant way of having a multi-line declaration of a dict?
note: Creating multiline strings in JavaScript is a solution only for strings. it doesn't work with a dict.
edit: I was adding a '\' at the end of each line. That was the issue. thanks.
var myDict = {
"aaa": true,
"aab": false,
"aac": false,
"aad": true,
[...]
};
I hope this is what you meant, because it's basic Javascript syntax.
Also, if for some reasons you want to "store" simple objects (made of strings, numbers, booleans, arrays or objects of the above entities) into strings, you can consider JSON:
var myDictJSON = '{\
"aaa": true,\
"aab": false,\
"aac": false,\
"aad": true,\
[...]
}';
var myDict = JSON.parse(myDictJSON);
Support for JSON is native for all the major browsers, including IE since version 8. For the others, there's this common library json2.js that does the trick.
You can also convert your simple objects into string using JSON.stringify.
that's easy-
var myDict={
"aaa":true,
"aab":false,
"aac":false,
"aad":true
};
please remember, don't place the curly bracket in the next line.
i like responses. Please respond
This (a complex data structure containing both "string" and "booleans"):
var myDict={"aaa":true,"aab":false,"aac":false,"aad":true, [...] };
Can be expressed like this:
var myDict={
"aaa":true,
"aab":false,
"aac":false,
"aad":true,
[...]
};
Similarly, this:
var myBigHairyString = "Supercalifragilsticexpialidocious";
Can be expressed like this:
var myBigHairyString =
"Super" +
"califragilstic" +
"expialidocious";

Categories