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