Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reference object when destructuring

Tags:

javascript

I'm playing with destructuring:

function create(){
 let obj={a:1,b:2}
obj.self=obj
 return obj
}
const {a,self} = create()

Is there a way to get the self object without adding such a property ?

function create(){
 let obj={a:1,b:2}
// removes   obj.self=obj
 return obj
}
const {a,this} = create()

In one line of code if possible!

Thank you in advance for your help.

like image 368
Alphapage Avatar asked Jul 05 '17 17:07

Alphapage


1 Answers

You can wrap your create return value inside a temporary outer object, and then access the original object by property name from the outer object. This still allows you to pull out properties from the original object as well.

const {me:{a}, me} = {me:create()}

This will create the variable a using the property a from the object, and create the variable me which holds the entire object.

Or, to name it something other than the property name from the outer object (e.g., foo instead of me):

const {me:{a}, me:foo} = {me:create()}

This still requires making an additional property, but the property exists on the instantly-disposed wrapper object. This can be done entirely external to create so you don't need to touch the process of how the create function operates just to make it destructuring-friendly.

like image 119
apsillers Avatar answered Oct 03 '22 14:10

apsillers