4

I have one complex object and want to extract some keys and apply some function and assign it with some other variable name and using object destructuring syntax but couldn't find any solution to apply.

const alpha = { a: 'lower', b: '23.45' };
const { a: newA.toUpperCase(), b: parseFloat(floatB)}  = alpha;

I know this is wrong because here newA and floatB is yet not defined.

Even I tried

const { a:a.toUpperCase(), b: parseFloat(b)} = alpha;

But that also not work

So my question is how can we achieve somehow.

Or we need to do it later once assign as new variable name?

xkeshav
  • 53,360
  • 44
  • 177
  • 245
  • Just don't use destructuring here. `const newA = alpha.a.toUpperCase(), floatB = parseFloat(alpha.b);` is simpler, shorter and more readable. – Bergi Jun 20 '19 at 17:47
  • it's a simple case I have explain in OP..there is deepdown property I want to extract. – xkeshav Jun 20 '19 at 17:48
  • 1
    You might want to show your actual case then. But still, it's not possible, you will need an extra step after accessing the deep properties. – Bergi Jun 20 '19 at 17:50

1 Answers1

3

You can't do that at the same time. In spite of the destructuring you're declaring / creating variables. While you're creating variables you can't execute a function.

So, STEP 1 -> Destructure what you need from alpha. STEP 2 -> execute the functions you need

evedes
  • 79
  • 4
  • But in general we can execute the function while creating variables for eg. ` let x = b.toUpperCase()` – xkeshav Jun 20 '19 at 17:32
  • 1
    that's a particular case where you're appending / chaining .toUpperCase because it exists in the prototype chain of b. – evedes Jun 20 '19 at 17:39
  • You can also destructure methods from the prototype chain. For example const a = [1,2,3,4] Now if you do { length } = a and console.log(a) you get 4. Again, because it's a method that exists on the prototype chain. – evedes Jun 20 '19 at 17:41
  • you means `a.prototype.toUpperCase(): newA` will work ! – xkeshav Jun 20 '19 at 17:43
  • @evedes Actually `length` is not a prototype method (or getter), but an instance property – Bergi Jun 20 '19 at 17:48
  • I suppose that while destructuring you can't do that. Also, it's not a good practice. Keep things as simple and stupid as you can. Anyways, if you want to deep dive into destructuring I leave you this link: https://github.com/getify/You-Dont-Know-JS/blob/master/es6%20%26%20beyond/ch2.md from Kyle Simpson. – evedes Jun 20 '19 at 17:54
  • True story @bergi, sorry for the mistake. That's why you can destructure length and log the value. Not a method. – evedes Jun 20 '19 at 17:58
  • @evedes Although you were right, one *can* destructure methods and inherited properties - it's just that your example didn't fit. Rather: `const a = [1,2]; const { push } = a; push.call(a, 3); console.log(a);` – Bergi Jun 20 '19 at 18:15