36

How can I rename the target during object destructing?

const b = 6;
const test = { a: 1, b: 2 };
const {a, b as c} = test; // <-- `as` does not seem to be valid in ES6/ES2015
// a === 1
// b === 6
// c === 2
Jack Allan
  • 14,554
  • 11
  • 45
  • 57
  • 1
    Have you tried `{a, b: c} = test`? – vaultah Jan 20 '16 at 15:53
  • 3
    `{b as c}` is for ES6 import syntax, which is very much _not_ destructuring FYI. Misunderstanding that difference can lead to confusion around how modules work. – loganfsmyth Jan 20 '16 at 19:35
  • Related: [Object destructuring with property names that are not valid variable names](https://stackoverflow.com/q/36577568/1048572) – Bergi Jun 17 '17 at 11:14
  • Related: [Destructuring and rename property](https://stackoverflow.com/q/57065348/1048572) – Bergi Feb 09 '22 at 23:19

1 Answers1

69

You can assign new variable names, like shown in this MDN Example

var o = { p: 42, q: true };

// Assign new variable names
var { p: foo, q: bar } = o;

console.log(foo); // 42
console.log(bar); // true  

So, in your case, the code will be like this

const b = 6;
const test = { a: 1, b: 2 };
let { a, b: c } = test;
console.log(a, b, c); // 1 6 2

Online Babel Demo

adiga
  • 34,372
  • 9
  • 61
  • 83
thefourtheye
  • 233,700
  • 52
  • 457
  • 497