Working with bad data from backend, I need to convert strings to integers.
I have JSON:
{
"cars": [
"36",
"49",
"73"
]
}
I have an attempt to convert the strings to integers.
let cars= res.data.products[0].cars;
for (const key of Object.keys(cars)) {
setSelectedCars(selCars=> [...selCars, parseInt(cars, 0)]);
}
This attempt does not work as I loop it wrong and end with single value being present multiple times in array while "" remains.
The desired outcome would thus be:
{
"cars": [
36,
49,
73
]
}
CodePudding user response:
Just use map
and convert each to a number
.
const data = {
"cars": [
"36",
"49",
"73"
]
}
data.cars = data.cars.map(Number);
console.log(data);