简体   繁体   中英

Change the data type in the array of Objects

I have the array of Objects as follows

Object {Results:Array[2]}
    Results:Array[2]
    [0-1]
      0:Object
             id=1     
             name: "Rick"
             Value: "34343"
      1:Object
             id=2     
             name:'david'
             Value: "2332"

As you can see, the Value field in the array of Objects is a string. I want all these to be converted to a number instead.

The final data should look like this. can someone let me know how to achieve this please.

Object {Results:Array[2]}
    Results:Array[2]
    [0-1]
      0:Object
             id=1     
             name: "Rick"
             Value: 34343
      1:Object
             id=2     
             name:'david'
             Value: 2332

You can convert a number literal into a number using a + prefix:

 var input = { Results: [{ id: 1, name: "Rick", Value: "34343" }, { id: 2, name: 'david', Value: "2332" }] } for (var i = 0; i < input.Results.length; i++) { input.Results[i].Value = +input.Results[i].Value; } console.log(input); 

Just call .parseInt() on each of your "Value" fields. For example: `

for(var i in Results){
   if(Results[i].Value != ""){
       Results[i].Value = parseInt(Results[i].Value);
   }`
}

You can map data.Results and use parseInt() on the Value properties:

data.Results = data.Results.map(function(d) {
    d.Value = parseInt(d.Value, 10);
  return d;
}); 

console.log(data);

However, why do you need this? Maybe you should consider to do the parsing once you actually access the data...

If you can do this in a basic way, it will look like:

function convertArrayValues (array) { // obj.Results goes here
  // cloning can be ommited
  var array = JSON.parse(JSON.stringify(array));
  for(var i = 0; i < array.length; i++) {
    array[i].Value = parseFloat(array[i].Value);
  }
  return array;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM