Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Given an array of json objects, how do I convert values in each object to an int or float?

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.

like image 967
AtHeartEngineer Avatar asked Mar 07 '23 11:03

AtHeartEngineer


1 Answers

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

like image 166
jithin john Avatar answered Mar 10 '23 04:03

jithin john