0

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

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

1 Comment

Hi. "Try this" isn't particularly useful. You should describe with links to documentation what you've done to solve the problem.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.