AR7 AR7 - 5 months ago 13x
Javascript Question

Is it possible to do an atomically update all the keys in an object? Something like splice for an array?

I'm currently working on some undo/redo functionality for a project I'm working on.

Keeping a clean history that enables a good undo/redo means that changes should be atomic because otherwise, the undo/redo will step through the small changes made in a single operation as if they were individual changes themselves.

For arrays, this is possible with

, but I'm not sure if there is an equivalent for objects. It would need to atomically mutate every value in the object like a splice does for an array.

I would also like to point out that immutable values aren't an option for this project as it relies completely on mutation for everything.


JSBin Example

You could use Object.assign to do this:

var obj = {a:1, b:2};
var next = {a: 3, b: 4};

var x = Object.assign(obj, next);

console.log(x);// { a: 3, b: 4 }
console.log(obj);// { a: 3, b: 4 }