Remove double quotes from array in JavaScript - javascript

How to remove double quotes from array in JavaScript?
my data, this polygon coordinates google maps
["{lat:-8.089057558100306,lng:112.15251445770264}", "{lat:-8.100954123313068,lng:112.15251445770264}", "{lat:-8.100954123313068,lng:112.1782636642456}", "{lat:-8.087867882261257,lng:112.17800617218018}", "{lat:-8.089057558100306,lng:112.15251445770264}"]
to
[{lat:-8.089057558100306,lng:112.15251445770264}, {lat:-8.100954123313068,lng:112.15251445770264}, {lat:-8.100954123313068,lng:112.1782636642456}, {lat:-8.087867882261257,lng:112.17800617218018}, {lat:-8.089057558100306,lng:112.15251445770264}]
after remove double quotes my data must be still array, not string.
Thanks

If you can't alter the results you get above, you have to work around it.
var a = ["{lat:-8.089057558100306,lng:112.15251445770264}", "{lat:-8.100954123313068,lng:112.15251445770264}", "{lat:-8.100954123313068,lng:112.1782636642456}", "{lat:-8.087867882261257,lng:112.17800617218018}", "{lat:-8.089057558100306,lng:112.15251445770264}"];
a = a.map(function(o){
var d = o.split(',').map(function(b){
return Number( b.replace(/(}|{lat:|lng:)/g, '') );
/* OR
b.replace('{lat:', '')
.replace('lng:', '')
.replace('}', '');
*/
});
return {
lat: d[0],
lng: d[1]
};
});
console.log(a);

Iif you really trust that data, evaling it is the simplest way to convert it:
let data = ["{lat:-8.089057558100306,lng:112.15251445770264}", "{lat:-8.100954123313068,lng:112.15251445770264}", "{lat:-8.100954123313068,lng:112.1782636642456}", "{lat:-8.087867882261257,lng:112.17800617218018}", "{lat:-8.089057558100306,lng:112.15251445770264}"];
console.log(data.map(s => eval('null,' + s)));
(The null, is just there to make eval treat this as an expression instead of a { block }.)
However, as always, eval can introduce code injection vulnerabilities if you're not sure about where the data comes from. And really, you should figure out how the data got this way in the first place and fix it up into a useful format there.

You can try regex
var arr = ["{lat:-8.089057558100306,lng:112.15251445770264}", "{lat:-8.100954123313068,lng:112.15251445770264}", "{lat:-8.100954123313068,lng:112.1782636642456}", "{lat:-8.087867882261257,lng:112.17800617218018}", "{lat:-8.089057558100306,lng:112.15251445770264}"]
arr = arr.map(function(item) {
var match = item.match(/lat:(\-?[0-9\.]+),lng:(\-?[0-9\.]+)/);
return {lat: +match[1], lng: +match[2]};
})
console.log(arr)

Related

How to efficently parse a string of latitude/longitude points to an array of object in JS?

I receive a series of latitude/longitude points in a string (from a third party) with the following format (of course there can be more than 2 set of pairs):
[(49.0000, -105.0000), (49.0000, -110.0000)]
and I want to convert that string to an array of object like this:
[{lat: 49.0000, lng: -105.0000}, {lat: 49.0000, lng: -110.0000}]
I want to do this in pure JavaScript but would be open to use jQuery if it simplifies the code a lot.
Currently, I use some regex and substrings on the source string but I'm wondering if there more elegant way to do this conversion that I could have missed?
You can try:
// your third party string
var string = '[(49.0000, -105.0000), (49.0000, -110.0000)]';
// make it a valid array of positions
// - basically changing parentheses to brackets
var array = string.replace(/[()]/g, function(d){
return {
'(' : '[',
')' : ']',
}[d];
});
// now it is valid, parse it
array = JSON.parse(array);
// each item has lat/long in the positions 0/1, respectively
var result = array.map(function(item){
return {
lat: item[0],
lng: item[1],
};
});
console.log(result);
Use JSON.parse(dataString) to achieve array of objects with lat/lng fields. If it's not solve your problem, than provide addition information.

Replacing values in JSON object

I have the following JSON object data returned from my apicontroller :
[
{"id":2,"text":"PROGRAMME","parent":null},
{"id":3,"text":"STAGE","parent":2},
{"id":4,"text":"INFRA","parent":2},
{"id":5,"text":"SYSTEM","parent":3},
{"id":6,"text":"STOCK","parent":3},
{"id":7,"text":"DPT","parent":3},
{"id":9,"text":"EXTERNAL","parent":null}
]
I want to replace "parent":null with "parent":'"#"'
I have tried the code below, but it is only replacing the first occurrence of "parent":null. How can I replace all "parent":null entries?
$(document).ready(function () {
$.ajax({
url: "http://localhost:37994/api/EPStructures2/",
type: "Get",
success: function (data) {
var old = JSON.stringify(data).replace(null, "'#'"); //convert to JSON string
var new = JSON.parse(old); //convert back to array
},
error: function (msg) { alert(msg); }
});
});
Thanks,
You need to make the replace global:
var old = JSON.stringify(data).replace(/null/g, '"#"'); //convert to JSON string
var newArray = JSON.parse(old); //convert back to array
This way it will continue to replace nulls until it reaches the end
Regex docs:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp
Also, as a side note, you should avoid using new as a variable name as it is a reserved word in javascript and most browsers will not allow you to use it
#JonathanCrowe's answer is correct for regex, but is that the right choice here? Particularly if you have many items, you'd be much better off modifying the parsed object, rather than running it through JSON.stringify for a regex solution:
data.forEach(function(record) {
if (record.parent === null) {
record.parent = "#";
}
});
In addition to being faster, this won't accidentally replace other nulls you want to keep, or mess up a record like { text: "Denullification Program"}.

concatenate string from JSON

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

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