I have an array of objects with three properties each (year, total, per_capita). Example:
0: Object
per_capita: "125.8"
total: "1007.2"
year: "2009"
Those properties are strings and I want to create a loop that goes through the array and converts them to int. I tried the following loop:
for (i=0; i<data.length; i++){
parseInt(data[i].year, 10)
parseInt(data[i].total, 10)
parseInt(data[i].per_capita, 10)
}
However when I do typeof(data[0].total) it says its a string. I am having problems later in the program and I think it is because the values cannot be computed properly because they are not the right type. Anyone have an idea where the problem is?
I have an array of objects with three properties each (year, total, per_capita). Example:
0: Object
per_capita: "125.8"
total: "1007.2"
year: "2009"
Those properties are strings and I want to create a loop that goes through the array and converts them to int. I tried the following loop:
for (i=0; i<data.length; i++){
parseInt(data[i].year, 10)
parseInt(data[i].total, 10)
parseInt(data[i].per_capita, 10)
}
However when I do typeof(data[0].total) it says its a string. I am having problems later in the program and I think it is because the values cannot be computed properly because they are not the right type. Anyone have an idea where the problem is?
Share Improve this question asked Oct 3, 2016 at 17:08 samzmannsamzmann 2,5665 gold badges23 silver badges49 bronze badges 1- really int not float? you are loosing precision. – Nina Scholz Commented Oct 3, 2016 at 17:25
4 Answers
Reset to default 12This should help!
var a = {
per_capita: "125.8",
total: "1007.2",
year: "2009",
}
Object.keys(a).forEach(function(el){
a[el] = parseInt(a[el])
})
console.log(a)
console.log(typeof a.total)
parseInt does not mutate objects but parses a string and returns a integer. You have to re-assign the parsed values back to the object properties.
for (i=0; i<data.length; i++){
data[i].year = parseInt(data[i].year, 10)
data[i].total = parseInt(data[i].total, 10)
data[i].per_capita = parseInt(data[i].per_capita, 10)
}
All you did was the conversion, but you missed the assignment:
for (i=0; i<data.length; i++){
data[i].year = parseInt(data[i].year, 10)
data[i].total = parseInt(data[i].total, 10)
data[i].per_capita = parseInt(data[i].per_capita, 10)
}
The parseInt
function returns the int value, it doesn't change the input variable.
Another thing - if you need the total number to be float you should use the parseFloat
function and not the parseInt
.
You could iterate the array and the object amd assign the integer value of the properties, you want.
data.forEach(function (a) {
['year', 'total', 'per_capita'].forEach(function (k) {
a[k] = Math.floor(+a[k]);
});
});