I am trying to experiment around destructuring assignment. Now I have a case which I trying to cop up with destructuring itself.
For example, I have an input like this:
let input = {latitude: "17.0009", longitude: "82.2108"}
Where latitude
and longitude
key values are strings, but I want to parse them into a number while destructuring.
let input = {latitude: "17.0009", longitude: "82.2108"}
let {latitude,longitude} = input
console.log(typeof latitude,typeof longitude)
I can see in babel repl that this takes a reference of an object and then access each key. So the above code is the same as:
"use strict";
var arr = {
latitude: "17.0009",
longitude: "82.2108"
};
var latitude = arr.latitude,
longitude = arr.longitude;
I want do something like using the destructuring syntax itself.
"use strict";
var arr = {
latitude: "17.0009",
longitude: "82.2108"
};
var latitude = Number(arr.latitude),
longitude = Number(arr.longitude);
I am open to see some hacks too.
Update
I am able to come with up one hack with the ,
operator:
let arr = {latitude: "17.0009", longitude: "82.2108"}
let {lat,lng} = ({latitude,longitude} = arr, ({lat:+latitude,lng:+longitude}))
console.log(typeof lat, typeof lng)
On side note:- you must read Moritz Roessler's answer this is hacky but contains good knowledge and information
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 ]