Gán property nested bằng string path (ví dụ: "a.b.c") dễ lỗi nếu path không tồn tại. Nên dùng **Lodash _.set()** hoặc optional chaining.
Lodash _.set(object, path, value)
const _ = require('lodash');
let obj = { a: { b: { foo: 'test' }, c: 2 } };
_.set(obj, 'a.b.foo', 'test1');
_.set(obj, 'a.c', { test2: 'bar' });
console.log(obj); // { a: { b: { foo: 'test1' }, c: { test2: 'bar' } } }
Custom setUpdateProp (no dependency)
const setUpdateProp = (object, path, value) => {
if (path.length === 1) { object[path[0]] = value; return; }
if (path.length === 0) throw new Error('Empty path');
if (!object[path[0]]) object[path[0]] = {};
setUpdateProp(object[path[0]], path.slice(1), value);
};
setUpdateProp(obj, ['level1', 'level2'], 'FooBar');
Native: Optional Chaining + Assignment (ES2020)
obj.a?.b = obj.a?.b ?? {}; // ensure path exists
obj.a.b.foo = 'test1';
Khuyến nghị: Lodash cho dynamic path string. Optional chaining cho static path. Tránh eval hoặc new Function.