问题
I'm attempting to use the rest operator and restructuring to omit an entry in the object. Based on the documentation, rest should no longer include the key entry 575. After the operation, rest still has the same keys as state. I'm not sure what I'm doing wrong. Thanks in advance.
book = {
id: 575,
title: "Vector Calc"
};
state = {
removedBooks: {
46: {
id: 46,
title: "economics"
},
575: {
id: 575,
title: "Vector Calc"
}
}
};
const {
[book.id]: data, ...rest
} = state;
console.log(rest);
EDIT: I am using React and it is not recommended to mutate the state object directly. Why can't I directly modify a component's state, really? among others
回答1:
The books are part of the removedBooks
property, and are not direct children of the state
. You need to destructure the removedBooks
property as well.
const book = {"id":575,"title":"Vector Calc"};
const state = {"removedBooks":{"46":{"id":46,"title":"economics"},"575":{"id":575,"title":"Vector Calc"}}};
const { removedBooks: { [book.id]: data, ...removedBooks } } = state;
const newState = { ...state, removedBooks };
console.log(newState);
回答2:
Your destructuring assignment expects a pattern of { 575: data, ...other... }
but state
actually has { removedBooks: { 575: data, ...other... } }
. Add the removedBooks
into your destructuring assignment and it works fine.
book = {
id: 575,
title: "Vector Calc"
};
state = {
removedBooks: {
46: {
id: 46,
title: "economics"
},
575: {
id: 575,
title: "Vector Calc"
}
}
};
const { removedBooks: {
[book.id]: data, ...rest
} } = state;
console.log(rest);
来源:https://stackoverflow.com/questions/64000577/rest-operator-to-omit-properties