const createPlainObj = (nested, path = '') =>
Object.entries(nested).reduce((obj, [ k, v ]) => {
const newPath = `${path}${path ? '.' : ''}${k}`;
return Object.assign(obj, v instanceof Object
? createPlainObj(v, newPath)
: { [newPath]: v }
);
}, {});
const plain = createPlainObj(example, 'example');
const buildNestedObj = (source, target = {}) =>
Object.entries(source).reduce((acc, [ path, val ]) => {
const keys = path.split('.');
const key = keys.pop();
keys.reduce((p, c) => p[c] = p[c] || {}, acc)[key] = val;
return acc;
}, target);
const obj = {};
_.set(obj, 'user.id', 5);
console.log(obj); // { user: { id: 5 } }