How do I parse a string to number while destructuring?

You could have a reusable function, like this below:

const numberInputs = input =>
    Object.keys(input).reduce((acc, val) => {
        acc[val] = +input[val];
        return acc;
    }, {});

and then reuse it across...

Then do:

let {latitude,longitude} = numberInputs(input);

console.log(typeof latitude,typeof longitude) //number //number

and get 17.0009 and 82.2108 as numbers...

This way you keep your original object also and make a copy... so you have both original and copy of the object which has numbers as values...


Destructuring is just a nice way to unpack properties from objects and arrays and assign them to variables. As the trasnpiled code in the question suggests, any kind of operation is not possible.

One hack would be to create 2 more variables (which don't exist in input) and set the default value to the number equivalent of the previously destrucutred properties:

let input = { latitude: "17.0009", longitude: "82.2108" }
let { latitude, longitude, lat = +latitude, long = +longitude } = input

console.log(typeof latitude, typeof longitude, typeof lat, typeof long)

The code approximately trasnpliles to this (Babel):

var latitude = input.latitude,
    longitude = input.longitude,
    lat = input.lat === undefined ? +latitude : input.lat,
    long = input.long === undefined ? +longitude : input.long;

It's just exploiting the order in which the variables are created and assigned property values. Again, this works only if there are no lat or long properties in input. Otherwise, it will fail the ternary condition and lat will be set to input.lat.


Something like this would be much easier to read though:

let { latitude, longitude } = input;
let lat = +latitude, 
    long = +longitude;

OR

let [ lat, long ] = [ +latitude, +longitude ]

You could destructure the values, take an array of the values and map the a new data type of the value and assign this values back to the variables.

let input = { latitude: "17.0009", longitude: "82.2108" },
    { latitude, longitude} = input;

[latitude, longitude] = [latitude, longitude].map(Number);

console.log(typeof latitude, latitude);
console.log(typeof longitude, longitude);