I am using string.endswith()
to loop through JSON objects and find out if the any property of the object endswith
a "Value"
substring.
After finding out if the the object property ends with "Value"
, i am trying to round off the value of the property to 2 decimals which are by default 5 decimals.
Here is my code
var MyObj= [{"$id":"1","GeoName":"EAST","ReachValue":87.88221970554928,"ReachValue":90.71955219607294,"DepthValue":18.44377295716579,"ShareValue":16.732108234801206},{"$id":"2","GeoName":"WEST","ReachValue":87.88221970554928,"ReachValue":90.71955219607294,"DepthValue":18.44377295716579,"ShareValue":16.732108234801206}];
Obj = JSON.parse(JSON.stringify(MyObj)).map(function (e) {
return Object.keys(e).reduce(function (p, n) {
if (n.endsWith("Value"))
p[n] = Math.round(e[n] * 100) / 100;
else
p[n] = e[n];
return p;
}, {})
});
The above code works absolutely fine in chrome
and Firefox
, While IE it throws endsWith
is not a function exception.
I found out for such issues pollyfills are used, which i tried and i failed. I am not even sure if i used the pollyfill correctly.
so here is how i did it,
function polyFillEndswith(searchString, position) {
if (!String.prototype.endsWith) {
String.prototype.endsWith = function (searchString, position) {
var subjectString = this.toString();
if (typeof position !== 'number' || !isFinite(position) || Math.floor(position) !== position || position > subjectString.length) {
position = subjectString.length;
}
position -= searchString.length;
var lastIndex = subjectString.lastIndexOf(searchString, position);
return lastIndex !== -1 && lastIndex === position;
}
}
}
Obj = JSON.parse(JSON.stringify(BubbleObj)).map(function (e) {
return Object.keys(e).reduce(function (p, n) {
if (n.polyFillEndswith("Value", "0"))
p[n] = Math.round(e[n] * 100) / 100;
else
p[n] = e[n];
return p;
}, {})
});
is the above code even correct? if not how can i change it to achieve my objective?
The polyfill function you have is actually for attaching the endsWith
function to the native String
object, which JavaScript allows you to do. It will allow you to call endsWith
like normal.
Instead of wrapping it in a function, let it run right away, then just use the normal endsWith
:
if (!String.prototype.endsWith) {
String.prototype.endsWith = function (searchString, position) {
var subjectString = this.toString();
if (typeof position !== 'number' || !isFinite(position) || Math.floor(position) !== position || position > subjectString.length) {
position = subjectString.length;
}
position -= searchString.length;
var lastIndex = subjectString.lastIndexOf(searchString, position);
return lastIndex !== -1 && lastIndex === position;
}
}
Obj = JSON.parse(JSON.stringify(BubbleObj)).map(function (e) {
return Object.keys(e).reduce(function (p, n) {
if (n.endsWith("Value"))
p[n] = Math.round(e[n] * 100) / 100;
else
p[n] = e[n];
return p;
}, {})
});