Reputation: 426
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
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