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
4 Answers
Reset to default 4You 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;
}