Let's assume that I've the following object:
let filters = {
brands: { ... },
price: { ... },
sizes: { ... },
...
}
The properties of the filters
object will be set by the users. Which means sometimes the filters
object may contain just brands
, sometimes it may contain brands
& price
and so on.
I've written the following function to extract a specific property from the filters
object:
let extractProperty = (propertyName) => {
({ propertyName, ...rest } = filters); // <-- propertyName isn't working here
console.log(propertyName);
}
extractProperty("brands");
If I invoke the above function, the console displays undefined
.
Can anyone please point me out what I'm missing here?
Note:
I've already resolved this issue using lodash.omit method. But I'm still curious to know why function parameter value isn't working in object-destructuring.
Not Duplicate:
That code is looking for a property called
propertyName
, literally. To use the value inpropertyName
as the property name, you need to use computed notation, and you'll need to specify where to put the property's value. For instance, to put it in an existingexample
variable:Your code is written assuming that
rest
already exists, but I suspect you really want to declare it locally, along with the variable to receive the property value:Without
const
,let
(orvar
, butvar
is deprecated), unless you haverest
declared in an enclosing scope, that code will either fail with aReferenceError
(in strict mode) or fall prey to what I call The Horror of Implicit Globals (in loose mode), automatically creating a global variable.