WindCheck
WindCheck

Reputation: 426

Spread operators with variable as Rest Parameter

I want to filter data using spread operator. I have a function that has category as its argument.

The problem is when I pass category as arg to the spread operator I got an obvious error: The symbol "category" has already been declared.

How can I use category instead of the hardcoded "Headlines"?

const data = {
    "subscription": {
        "Headlines": ["headline1", "headline1"],
        "News": ["news1"],
    }
}
const category = "Headlines";
// const { category, ...rest } = data.subscription; This does not work.
const { Headlines, ...rest } = data.subscription; // This works.
const updatedData = {...data, subscription: rest};
console.log(updatedData);

Upvotes: 0

Views: 54

Answers (1)

Majed Badawi
Majed Badawi

Reputation: 28424

In order to deconstruct a dynamic property, you can use square brackets [] and assign the destructured value to a variable name:

const data = {
  "subscription": {
    "Headlines": ["headline1", "headline1"],
    "News": ["news1"],
  }
};

const category = "Headlines";
const { [category]: categoryProp, ...rest } = data.subscription;

const updatedData = {...data, subscription: rest};
console.log(updatedData);

Upvotes: 2

Related Questions