How can I replace JSON.stringify variable with K and A variable with my own variable
I want my polygon points to hit the database via ajax. So I used this like
function StorePolygon(id, poly_points) {
var html;
// The values of id=1001 and poly_points=((47.53208121578362, 7.705052197034092),
// (47.53188401121172, 7.704971730763646),(47.53189169452062, 7.705076336915226))
$.ajax({
url: url_prefix + "SetPolygonInfo",
data: ({
'id': id,
'polypoints': JSON.stringify(poly_points),
'as_json': 1
}),
async: false,
dataType: "json",
success: function(result) {
html = result.html;
},
error: function(data, status, e) {
alert(e);
}
});
return html;
}
JSON.stringify (poly_points) produces like this,
[{"k":47.53208121578362,"A":7.705052197034092},
{"k":47.53188401121172,"A":7.704971730763646},
{"k":47.53189169452062,"A":7.705076336915226}]
I want to use my own variable instead of K and A. Can anyone help?
+3
source to share
2 answers
I just don't want to depend on JSON.stringify (poly_points) variables to be stored in the DB. So i liked it
function StorePolygon(id, poly_points) {
var html;
var olist = []
var obj = {}
/*
JSON.stringify(poly_points.map(function(point) {
obj = {
'x': point.k,
'y': point.B
}
olist.push(obj)
}))*/
for(var i=0;i<poly_points.length;i++){
var xy = poly_points[i];
obj = {
'x': xy.lat(),
'y': xy.lng()
}
olist.push(obj)
}
$.ajax({
url: url_prefix + "SetPolygonInfo",
data: ({
'id': id,
'poly_points': JSON.stringify(olist),
'as_json': 1
}),
async: false,
dataType: "json",
success: function(result) {
html = result.html;
},
error: function(data, status, e) {
alert(e);
}
});
return html;
}
It worked great. JSON.stringify (poly_points) sometimes gives k and A
[{"k":47.53208121578362,"A":7.705052197034092},
{"k":47.53188401121172,"A":7.704971730763646},
{"k":47.53189169452062,"A":7.705076336915226}]
but several times he gives
[{"k":47.53208121578362,"B":7.705052197034092},
{"k":47.53188401121172,"B":7.704971730763646},
{"k":47.53189169452062,"B":7.705076336915226}]
So I don't want the object / return list to depend on variables.
0
source to share
You can use a map to create a new array of objects that have the keys you want to use and instead of JSON.stringify this array:
JSON.stringify( poly_points.map(function (point){
return {
custom_key_for_k : point.k,
custum_key_for_A : point.A
};
}) )
You need to shim map support up to Internet Explorer 9 or use an equivalent function from any JavaScript library that includes it.
+3
source to share