Reputation: 6316
I have a dynamically loaded object for which the print of JSON.stringify()
in the console looks like this:
var data = [
{
"attributes": {
"OBJECTID": 1046
},
"geometry": {
"x": -9814734.1764,
"y": 5130578.545900002
}
},
{
"attributes": {
"OBJECTID": 1051
},
"geometry": {
"x": -9814335.3286,
"y": 5130497.9344
}
},
{
"attributes": {
"OBJECTID": 1052
},
"geometry": {
"x": -9814639.1784,
"y": 5130583.1822
}
},
{
"attributes": {
"OBJECTID": 1053
},
"geometry": {
"x": -9814496.7964,
"y": 5130560.822300002
}
}
];
How can I apply .toFixed(2)
function to each of X
and Y
in geometry
nodes on the fly?
Upvotes: 0
Views: 205
Reputation: 199
Just iterate using the forEach function. Also make sure to parse the value using parseFloat
before calling the toFixed
function.
data.forEach(entry => {
entry.geometry.x = parseFloat(entry.geometry.x).toFixed(2);
entry.geometry.y = parseFloat(entry.geometry.y).toFixed(2);
});
Upvotes: 0
Reputation: 2138
Try this
//Your Data
var data = [
{
"attributes": {
"OBJECTID": 1046
},
"geometry": {
"x": -9814734.1764,
"y": 5130578.545900002
}
},
{
"attributes": {
"OBJECTID": 1051
},
"geometry": {
"x": -9814335.3286,
"y": 5130497.9344
}
},
{
"attributes": {
"OBJECTID": 1052
},
"geometry": {
"x": -9814639.1784,
"y": 5130583.1822
}
},
{
"attributes": {
"OBJECTID": 1053
},
"geometry": {
"x": -9814496.7964,
"y": 5130560.822300002
}
}
];
//Updating data
data.forEach(function(item,index){
item["geometry"]["x"]=item["geometry"]["x"].toFixed(2);
item["geometry"]["y"]=item["geometry"]["y"].toFixed(2);
})
console.log(JSON.stringify(data))
Upvotes: 0
Reputation: 68443
Use map
data = data.map( function(s){
s.geometry.x = s.geometry.x.toFixed(2);
s.geometry.y = s.geometry.y.toFixed(2);
return s;
})
Edit
Or with forEach
data.forEach( function(s){
s.geometry.x = s.geometry.x.toFixed(2);
s.geometry.y = s.geometry.y.toFixed(2);
})
Upvotes: 1
Reputation: 20885
You need to use the map function:
const formattedData = data.map(d => {
d.geometry.x = parseFloat(d.geometry.x).toFixed(2);
d.geometry.y = parseFloat(d.geometry.y).toFixed(2);
return d;
})
Feel free to change the property name (x
-> xFormatted
) if you don't wish to override the original data.
Upvotes: 2