1

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

2 Answers2

3

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);
Ori Drori
  • 183,571
  • 29
  • 224
  • 209
  • Thank you @Ori. This definitively works in my chrome console. However, in my react component, I'm getting the wrong output. Im going to create another question focusing on that. It would be great if you can look at it. – Biniyam Asnake Sep 22 '20 at 01:39
  • https://stackoverflow.com/questions/64002070/rest-operator-for-deleting-property-in-object-not-working-in-react-component – Biniyam Asnake Sep 22 '20 at 01:59
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);
Klaycon
  • 10,599
  • 18
  • 35