最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Change the data type in the array of Objects - Stack Overflow

programmeradmin0浏览0评论

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

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
Share Improve this question asked Sep 6, 2016 at 22:04 Akanksha IyerAkanksha Iyer 1292 gold badges4 silver badges7 bronze badges 0
Add a ment  | 

4 Answers 4

Reset to default 4

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;
}
发布评论

评论列表(0)

  1. 暂无评论