1

Say, I have an object

const range = { min: '10', max: '20' }

And I want to destructure it so that after that I have 2 variables:
- min with the value of 10 (not string '10'), and
- max with the value of 20

const { min, max } = range will only result to min with the value of '10' (not 10). What I want is the Number(10)

How could I do that? I did know a little bit about ES6 destructuring and did some research, tried different syntaxes but couldn't find a satisfied solution. Could anyone suggest one?

Conclude: There're very nice clever syntax in the answers below, but as to go with real code, I would just go with the more verbose but readable one:

const min = +range.min // or Number(range.min)
const max = -range.max // or Number(range.max)
Loi Nguyen Huynh
  • 8,492
  • 2
  • 29
  • 52
  • Not sure you can apply a function on that, destructuring is only assigning an object/array to a range of variables – oktapodia Sep 30 '19 at 17:03

3 Answers3

6

One way is to use two extra variable with +min and +max as default value,

const range = { min: '10', max: '20' }

const {min, max, numMin = +min, numMax = +max} = range

console.log(numMin, numMax)

Note:- here in above method make sure you use names for extra variable which are not available in object, else it won't use the default value


Another way is to use IIFE, transform the object values to numeric values before destructuring

const range = { min: '10', max: '20' }

const {min,max} = ( ({min,max}) => ( {min: +min, max: +max} ) )(range)

console.log(min,max)

In practical purpose or actual code i will not use such tricky ways because i prefer readability and it has it's own benefits

const range = {
  min: '10',
  max: '20'
}

const min = parseInt(range.min)
const max = parseInt(range.max)

console.log(max, min)
Code Maniac
  • 37,143
  • 5
  • 39
  • 60
5

You could take the destructured values in an array and destructure the mapped values again.

var range = { min: '10', max: '20' },
    { min, max } = range;        

[min, max] = [min, max].map(Number);

console.log(typeof min, min);
console.log(typeof max, max);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
  • Thank you, I do like this one but will just end up using `const min = Number(range.min); const max = Number(range.max);` in my code for better readability. – Loi Nguyen Huynh Sep 30 '19 at 17:27
0

I don't think you can do any conversion as part of a de-structuring operation, but you could try to do a transformation first.

If you had a function like this:

function parseKeys(obj) {
    const parsed = {};
    for (const key of Object.keys(obj)) {
        try {
            parsed[key] = parseInt(obj[key]);
        } catch () {}
    }

    return { ...obj, ...parsed };
}

Then you could have a one-liner like this:

const { min, max } = parseKeys(range);
TedCHoward
  • 151
  • 6