2

How to assign to Object via destructuring? For example

let parameter = {id : 10, username : 'john'}
let obj = {}
({id : obj.iduser, username : obj.user} = parameter)

Expected :

{iduser : 10, user : 'John'}

But, i got an error :

ReferenceError: obj is not defined

Reference : Exploring.JS - ES6 [ #10 - Destructuring ]

Ade Firman Fauzi
  • 377
  • 3
  • 15

2 Answers2

3

Terminating the let obj = {} line with a semicolon solves this:

let parameter = {id : 10, username : 'john'};
let obj = {};
({id : obj.iduser, username : obj.user} = parameter);
console.log(obj);
Ori Drori
  • 183,571
  • 29
  • 224
  • 209
  • Why downvote? This is correct ! Thanks :3 But I don't get it, why without semicolon ruined everything? I think JS will fine without semicolon? – Ade Firman Fauzi Mar 12 '18 at 08:18
  • There are some edge cases in which a semicolon is required for the browser to interpret the code correctly. – Ori Drori Mar 12 '18 at 08:21
1

You could destuct first and use shorthand properties for a new object.

let parameter = { id : 10, username : 'john' },
    { id: iduser, username: user } = parameter,
    obj = { iduser, user };
    
console.log(obj);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392