rest operator to omit properties

寵の児 提交于 2021-01-28 09:51:56

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!