Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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"?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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);

>Solution :

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);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading