I am trying to update few JSON values from string to numbers. I read about the "replacer" function from MDN and tried to make it work. However, there is no effect to the actual json output. Not sure what is going wrong here. Any help/suggestion here is much appreciated. Here’s something I tried:
const NUMBER_FIELDS = [
'count',
'age',
'hours',
];
const payload = {
"name": "John Doe",
"age": "35",
"country": "Canada",
"count": 4,
"hours": "100"
}
function replacer(key, value) {
NUMBER_FIELDS.forEach((field) => {
if (key && key === field && typeof value === 'string') {
return parseInt(value, 10);
}
return field;
});
return value;
}
const postBody = JSON.stringify(payload, replacer);
>Solution :
You had the right idea, but the issue is you are not going to return from a forEach.
Just check if the key exists in the array and if it does return it as a number.
const NUMBER_FIELDS = [
'count',
'age',
'hours',
];
const payload = {
"name": "John Doe",
"age": "35",
"country": "Canada",
"count": 4,
"hours": "100"
}
function replacer(key, value) {
return NUMBER_FIELDS.includes(key) ? +value : value;
}
const postBody = JSON.stringify(payload, replacer);
console.log(postBody);