简体   繁体   中英

Destructing object as function args

 const obj = { foo: 1, bar: 2 }; let fn = (...obj) => { console.log(foo, bar); // ReferenceError: foo is not defined }; fn(obj);

I basically want to use the object props directly inside the function without having to obj.foo or obj.bar .

Edited to add : I understand I can define the args manually ( { foo, bar } ), but I don't want to do that since the object is expected to have unknown / variable number of properties.

Destructuring for objects differs than array:

 const obj = { foo: 1, bar: 2 }; let fn = ({ foo, bar }) => { console.log(foo, bar); // ReferenceError: foo is not defined }; fn(obj); 


You could also use destructuring on values if you just want to loop over properties:

 const obj = { foo: 1, bar: 2 }; let fn = (values) => { console.log(...values); // ReferenceError: foo is not defined }; fn(Object.values(obj)); 

Does this help?

I assume you are after some properties that you do know about. But want to retain the others ?

 const obj = { foo: 1, bar: 2, unknown: 3, unknow: 4, }; let fn = ({ foo, bar, ...other}) => { console.log(foo, bar); console.log(other); }; fn(obj); 

This seems to be what you're going for, at least roughly, as it does have a pretty major caveat.

All I did is use the this keyword on the assumption that it also encapsulated the variable names in the context of the function. Of course, during testing I forgot about one major bit of information. The this keyword, when used in that context, defaults to the containing context. In this case, that is window . Hence, setting the key names on the window object pollutes the global scope, or whatever the containing scope is, although I have not tested this in a class based context.

 const obj1 = {varname1: "this is variable name 1", varname2: "this is variable name 2"}; function createsVars(obj) { var keys = Object.keys(obj); for (let i = 0; i < keys.length; i++) { this[keys[i]] = obj[keys[i]]; } console.log(varname1, "|", varname2); } createsVars(obj1); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM