JSFiddle - React, Tailwind, and code Playground
by Sergei Marochkin
JavaScript
const objectSetInternal = (objRef, arrPath, value, index = 0) => {
if (index != arrPath.length) {
const field = arrPath[index];
objRef[field] = objectSetInternal(objRef[field] || {}, arrPath, value, index + 1);
return objRef;
}
return value;
}
const objectSet = (obj, arr, value) => objectSetInternal(obj, arr, value);
const test = {
keepThis: true,
hello: {
keepThisToo: true,
},
};
objectSet(test, ['hello', 'my', 'dear', 'world'], 12345);
console.log(test.hello.my.dear.world); // 12345
console.log(test.keepThis); // true
console.log(test.hello.keepThisToo); // true