S N Sakib
S N Sakib

Reputation: 1172

Function parameter value isn't working in object-destructuring in JS

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?

CodePen Link

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:

  1. This question is about passing default value

Upvotes: 0

Views: 512

Answers (2)

apple apple
apple apple

Reputation: 10591

why use destructuring here when you just want to get a property?

let filters = {
  brands: { value:'b' },
  price: { value:'p' },
  sizes: { value:'s' },
}

let extractProperty = propertyName =>
  console.log(filters[propertyName])

extractProperty("brands");

Upvotes: 0

T.J. Crowder
T.J. Crowder

Reputation: 1074138

That code is looking for a property called propertyName, literally. To use the value in propertyName 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 existing example variable:

let extractProperty = (propertyName) => {
  ({ [propertyName]: example, ...rest } = filters);
//   ^−−−−−−−−−−−−^^^^^^^^^^
  console.log(example);
};

extractProperty("brands");

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:

let extractProperty = (propertyName) => {
  const { [propertyName]: example, ...rest } = filters;
  console.log(example);
};

extractProperty("brands");

Without const, let (or var, but var is deprecated), unless you have rest declared in an enclosing scope, that code will either fail with a ReferenceError (in strict mode) or fall prey to what I call The Horror of Implicit Globals (in loose mode), automatically creating a global variable.

Upvotes: 4

Related Questions