To convert a string to a number if and only if it is a valid number you could try a conversion function like
const stringToNumber = str => typeof str == "string" && +str == str ? +str: str;
- the type check makes sure boolean
true
and false
aren't converted to numbers and also prevents converting falsey values to zero.
- the
+
unary operator convverts a string operand to a number, or NaN
if the string does not adhere to the syntax of a numeric literal,
- the
==
tests if the explicit conversion performed by +
produces the same result as an implicit conversion. If they same are same return the converted result, if not return the string argument.
Demonstration to convert numeric string properties of an object to numbers:
const stringToNumber = str => typeof str == "string" && +str == str ? +str : str;
const numberProperties = inputObj => {
const outputObj = {};
Object.keys( inputObj).forEach( key=> {
outputObj[ key] = stringToNumber( inputObj[key]);
});
return outputObj;
}
console.log( numberProperties( {
key1: "2",
key2: 1,
key0: "0",
key02: 0,
key3: false,
key4: null,
key9: "09"
}));
Update (in response to comment)
JavaScript Object keys are string values: if a number is provided as a property name (e.g. inside square brackets when using array lookup notation) the number is automatically converted to a string for use as the property name.
The short answer to the question, when interpreted literally, is
"no, your can't convert the key values of an object, which are strings, to numbers inside the object's list of property names".
As an example, the keys of an Array object are strings:
const array = [1,2,3];
Object.keys(array).forEach(
key=> console.log( "key: %s (%s), value: %s (%s)",
key, typeof key, array[key], typeof array[key])
);