0

I am trying to do this in node js v8

management variable looks like this:

let management = {
    ip: '1.1.1.1',
    port: '443',
    username: 'admin',
    password: 'admin'   
}

constructor ({management,system,network,...other}) {

   this.management =  {
      ip ,
      port = 443,
      username = 'admin',
      password = 'admin',
    } = { ...management };
}

Any idea why I get the message

ip: ip , ^

ReferenceError: ip is not defined

Shouldn't the evaluation be right to left so management is destructed before trying to assign? Any idea on how to do this in a clear way without any more code?

Sorin B
  • 21
  • 2
  • What are you trying to do? – Rahul Sharma Jun 21 '18 at 10:15
  • this.management = { ip , port = 443, username = 'admin', password = 'admin', } = { ...management }; in this situation it checks for a variable ip and assign key as ip and value as value assigned to ip, if you need to set empty value to key you need to assign ip: '' – Akhil Aravind Jun 21 '18 at 10:15
  • It tries to assign `ip` variable to the `ip` property, but you don't have that variable. – pishpish Jun 21 '18 at 10:15
  • That part I got. I was hoping that the destruction of management would do that. Like when you do const { ip } = {...management} – Sorin B Jun 21 '18 at 10:20

1 Answers1

0

You get the error because you destructure into variables that you never declared anywhere, and in strict mode that causes an exception (instead of creating globals).

Btw, you cannot destructure and construct an object literal at the same time. Your code would only assign { ...management } to this.management anyway.

You're likely looking for

constructor ({management, system, network, ...other}) {
    const {ip, port = 443, username = 'admin', password = 'admin'} = management;
    this.management = {ip, port, username, password};
}

or

constructor ({management: {ip, port = 443, username = 'admin', password = 'admin'}, system, network, ...other}) {
    this.management = {ip, port, username, password};
}

or

constructor ({management, system, network, ...other}) {
    this.management = (({ip, port = 443, username = 'admin', password = 'admin'} => ({ip, port, username, password}))(management);
}
Bergi
  • 513,640
  • 108
  • 821
  • 1,164
  • Thanks. This makes sense. – Sorin B Jun 21 '18 at 10:27
  • I went for this const {ip,port,username,password, privateKey} = {...management}; this.management = { ip , port: port || 443, username: username || 'admin', password: password || 'admin', privateKey, }; Since if the future I need to change the proprety name. I think this is clearer to read. – Sorin B Jun 21 '18 at 10:31
  • Don't do `{...management}` when all you need is `management`. No need to create a new object there. – Bergi Jun 21 '18 at 11:08
  • Yes you are right. I use it because in other places in the code I need to change the prop name for example from ip to host and would prefer to keep everything as consistent as possible. – Sorin B Jun 21 '18 at 13:04