Set a nested value by dot/bracket path, creating containers
A form library stores field values in one nested object and updates them by path, for example 'shipping.address.lines[1]'. Implement setAtPath(target, path, value), which writes value at path inside target, creating any missing objects and arrays along the way.
setAtPath(target, path, value) // => target (the same reference)
'a.b[0].c' means the keys a, b, 0, c. 'a.0.c' means the same thing. A path may start with a bracket ('[2].name'). Empty segments (as in 'a..b') are ignored.['config.json', 'size'] has two keys.'0', '12', but not '01' or '-1').null in the way are replaced. Inherited properties (for example toString) are never reused.value at the last key. Mutate target and return it.target unchanged when the path has no keys, when target is not an object (for example null or a number), or when any key is '__proto__', 'constructor' or 'prototype'. These keys are blocked so user input can never modify shared prototypes.const form = { user: { name: 'Mo' } };
setAtPath(form, 'user.email', 'mo@example.com');
// => { user: { name: 'Mo', email: 'mo@example.com' } }
setAtPath(form, 'shipping.lines[1]', 'Flat 4');
// form.shipping => { lines: [ <empty>, 'Flat 4' ] } (lines is an array)
setAtPath({}, ['config.json', 'size'], 12);
// => { 'config.json': { size: 12 } }
setAtPath({ count: 5 }, 'count.total', 9);
// => { count: { total: 9 } } (the number 5 is replaced)
setAtPath({}, 'zip.01', 'x');
// => { zip: { '01': 'x' } } ('01' is not an index)
setAtPath({}, '__proto__.isAdmin', true);
// => {} (blocked, nothing is written)