简体   繁体   中英

Update immutable object without breaking immutability in javascript

If an object is Immutable in Javascript, how do I update its values and how do I get the updated value from its variable.

For example:


const todo = {
  text: 'Eat',
  completed: false
};

// To update todo completion to true
const updatedTodo = Object.assign({}, todo, { completed: true });

I can't reassign the new updatedTodo to Todo because I used const . If I change const to let and reassign it, doesn't that break immutability. I'm probably missing something.

todo is immutable but its properties aren't. You can change them either via Object.assign(todo, { completed: true}) (note how there's no empty object at the start, that way todo is actually modified), or you can simply set it via todo.completed = true .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM