Upsert

JavaScript pattern

The upsert pattern can be used to update a value in an object, or insert it if the key doesn't already exist.

Warning: Only one upsert can be done per object. If you need to insert multiple keys, use sequential until the file converges.


Apply with the Grit CLI
grit apply util_upsert

Simple test

BEFORE
hello({});

hello({ thing: 'two' });

hello({ hello: 'old-id' });

hello({ hello: 'old-string' });

hello({ king: 'old-string' });
AFTER
hello({ hello: 'world' });

hello({ thing: 'two', hello: 'world' });

hello({ hello: 'world' });

hello({ hello: 'world' });

hello({ king: 'old-string', hello: 'world' });

String key

It handles cases where the key is a string.

BEFORE
string_key({});

string_key({ 'hello-world': 'boss' });
AFTER
string_key({ 'hello-world': 'niceness' });

string_key({ 'hello-world': 'niceness' });