-3

I have a array :

Var array=[{"name":"May","data1":"1121.0"}]

I want to change it to :

Var array= [{"name":"May","data1":1121.0}]
amrender singh
  • 7,949
  • 3
  • 22
  • 28
surya
  • 3
  • 3
  • Please read [What is the difference between JSON and Object Literal Notation?](https://stackoverflow.com/questions/2904131/what-is-the-difference-between-json-and-object-literal-notation) – str Jun 25 '18 at 17:04
  • So do you know what fields are numbers? If yes, than loop over and convert them. – epascarello Jun 25 '18 at 17:04

4 Answers4

0

Looks like this has been answered before here

I'll summarize;

for(var i = 0; i < objects.length; i++){
    var obj = objects[i];
    for(var prop in obj){
        if(obj.hasOwnProperty(prop) && obj[prop] !== null && !isNaN(obj[prop])){
            obj[prop] = +obj[prop];   
        }
    }
}

console.log(JSON.stringify(objects, null, 2));

This does have a bug where 0 becomes null.

Jace
  • 144
  • 1
  • 9
  • `"0"` cast to a number through the addition operator doesn't become null. Also, I don't think it's necessary to use `hasOwnProperty` - it's JSON. It's not inheriting from anything. – zfrisch Jun 25 '18 at 17:11
  • @zfrisch [There's no such thing as a "JSON Object"](http://benalman.com/news/2010/03/theres-no-such-thing-as-a-json/). Either it is JSON (i.e. a string) or an object. – str Jun 25 '18 at 17:13
  • @str you're right,100% a misnomer on my part, but still kind of validates what I was saying. – zfrisch Jun 25 '18 at 17:15
0

You want to convert the value mapped to the "data1" key to be a number instead of a string.

There are many ways to accomplish this in JavaScript, but the best way to do so would be to use Number.parseFloat like so:

var array = [{"name":"May","data1":"1121.0"}];
array[0]["data1"] = Number.parseFloat(array[0]["data1"]);

console.log(array[0]["data1"]); // 1121

If you need to perform this action with multiple objects inside of array, you could do

var array = [{"name":"May","data1":"1121.0"}, {"name":"May","data1":"1532.0"}, etc.] // Note that this is not valid JavaScript
array.map(obj => {obj["data1"] = Number.parseFloat(obj["data1"]); return obj;});
Andres Salgado
  • 243
  • 2
  • 7
0

If I understood well, you only want to convert the value of data1, from "1121.0" to 1121.0, in other words from string to number.

To convert only that key (data1), you only need this:

array[0].data1 = parseFloat(array[0].data1)

If that's not what you want, please explain better your question

Damian Peralta
  • 1,846
  • 7
  • 11
0

You can simply check using Number.isNaN with an attempted cast to a number using the + operator. If it returns true then do nothing. If it's false then change the value of the parameter to a cast number.

var array=[{"name":"May","data1":"1121.0"}];
array.forEach(data => {
 for(let key in data) Number.isNaN(+data[key]) || (data[key] = +data[key])
});

console.log(array);
zfrisch
  • 8,474
  • 1
  • 22
  • 34