Given an array of json objects, how do I convert values in each object to an int or float?
var data = [{
"rank": "1",
"name": "Bill"
},
{
"rank": "2",
"name": "Ted"
},
{
"rank": "3",
"name": "John"
},
{
"rank": "4",
"name": "Jane"
}
]
The json objects I'm using are much larger, in both dimensions, so I am trying to figure out how I can use the map function to convert the "rank" part from a string
to an int
. There are other parts I want to convert to floats too, but right now sorting by "rank" sorts 1,10,11,12,etc
.
How can I do this? I'm using React/ES6/JSX/Babel, or whatever that amalgamation is.
You can use the map function
var data = [{"rank": "1","name": "Bill"},
{"rank": "2.4","name": "Ted"},
{"rank": "3","name": "John"},
{"rank": "4.5","name": "Jane"}];
data.map(d => d.rank = +d.rank);
console.log(data);
Check this Fiddler
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With