Let's explore a few ways to do immutable updates in js. We'll start with this data:
var data = {
foo: {
bar: 1,
baz: 2,
}
};
Object.assign is part of es6, it's ugly but it's standard.
var updated = Object.assign(
{},
data,
{
foo: Object.assign(
{},
data.foo,
{bar: 'updated'}
)
}
);
Object spread gives nicer code, but it's experimental syntax
var updated = {
...data,
foo: {
...data.foo,
bar: 'updated'
}
};
The react updates addon gives a decent syntax for deep updates. It's very flexible but still a bit clunky.
var update = require('react-addons-update');
var updated = update(data, {
foo: {
bar: {$set: 'updated'}
}
});
imset
is less powerful than the previous in that it can only
perform one update at a time.
It has, in my opinion, the best syntax, and only requires es6.
It's currently missing some tests, so I wouldn't recommend using it yet.
var imset = require('imset');
var updated = imset`${data}.foo.bar = 'updated'`;