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