Search code examples
javascriptjavascript-objects

Dynamically creating variables using the object key value pairs?


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 '='

Solution

  • 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);