-1

Here is the code :

let box = {   
        aaa:111,
        bbb:222,
        ccc:333,
        destruct: function() { 
                   let des = ( {bbb} = box);
                   return des; 
                }
};
   

box.destruct();
aaa // return error : aaa is not defined
bbb // return 222

While i could use this syntax let {aaa,bbb,ccc} = box which is great. There would be a case in the future where another pair of keys and values would be added inside the object, for example ddd : 444, eee:555. Thus the coding in destruct : function()..... had to be updated too.

I would like to improve the object destructuring coding by using eval() and Object.keys().join(). This is the far i can go

        destruct : function() { 
                    let str = Object.keys( box ).join(); // "aaa,bbb,ccc"
                    let des = eval( "{" + str + "} = box" );
                    return des;
}

box.destruct() // return Unexpected token '='

2 Answers2

0

So from the question, it seems like you are trying to dynamically create variables at run time using the object box key values, while you shouldn't be doing this. But if its the last option then you should do something like this below.

let box = {
  aaa: 111,
  bbb: 222,
  ccc: 333,
  destruct: function () {
    for (key in box) {
      eval(`${key} = ${box[key]}`);
    }
  },
};

box.destruct();

console.log(aaa, bbb, ccc);
namar sood
  • 1,580
  • 1
  • 9
  • 17
  • _"...while you shouldn't be doing this."_ why? is it because of the eval()? or the whole idea itself? – biskut nation Jul 03 '20 at 16:25
  • you can refer to this answer https://stackoverflow.com/questions/86513/why-is-using-the-javascript-eval-function-a-bad-idea , and also using this approach creates global variables which may override other important variables if not taken care of. – namar sood Jul 03 '20 at 16:33
  • Thanks! Will keep it my mind about the global variables. Maybe i will resort to fancy variable naming for time being. – biskut nation Jul 03 '20 at 16:55
0

Try setting the keys to window object

let box = {
  aaa: 111,
  bbb: 222,
  ccc: 333,
  destruct: function () {
    Object.assign(window, this, {destruct: undefined})
  },
};

box.destruct();

console.log(aaa, bbb, ccc);

let box = {
  aaa: 111,
  bbb: 222,
  ccc: 333,
  destruct: function () {
    for (key in this) {
      if (key == 'destruct') continue 
      window[key] = this[key]
    }
  },
};

box.destruct();

console.log(aaa, bbb, ccc);
User863
  • 19,346
  • 2
  • 17
  • 41