Set Value in Object at String Path
const object = {};
set(object, "a[0].b.c", 4);
console.log(object.a[0].b.c);
set(object, ["x", "0", "y", "z"], 5);
console.log(object.x[0].y.z);
console.log(object);
// 4
// 5
{
a: [
{
b: {
c: 4,
},
},
],
x: [
{
y: {
z: 5,
},
},
],
};
function helper(object, path, value) {
const [current, ...rest] = path;
if (rest.length > 0) {
if (!object[current]) {
const isNumeric = !isNaN(rest[0]);
object[current] = isNumeric ? [] : {};
}
if (typeof object[current] === "object") {
const isNumeric = !isNaN(rest[0]);
object[current] = helper(isNumeric ? [] : {}, rest, value);
} else {
object[current] = helper(object[current], rest, value);
}
} else {
object[current] = value;
}
return object;
}
function set(object, path, value) {
let pathArr = path;
if (typeof pathArr === "string") {
pathArr = pathArr.replaceAll("[", ".").replaceAll("]", "").split(".");
}
// Recursive helper
helper(object, pathArr, value);
}