1

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
0

4 Answers 4

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);

Sign up to request clarification or add additional context in comments.

Comments

2

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);
   }`
}

Comments

0

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...

Comments

0

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;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.