Object Set Nested Value

Set a value at a nested path in an object using dot notation.

Code

General
const o = structuredClone(obj);
const parts = path.split('.');
let current = o;
for (let i = 0; i < parts.length - 1; i++) {
  current[parts[i]] = current[parts[i]] || {};
  current = current[parts[i]];
}
current[parts[parts.length - 1]] = value;
return o;

Parameters

Object to modify

Key path (dot notation)

Value to set

Browser·fetch() may be limited by CORS

More JavaScript Snippets