const Obj = {
level1_1: "Value1",
level1_2: "Value2",
level1_3: "Value3",
level1_4: "Value4",
level1_5: {
level2_1: {
level3_1: { level4_1:1, level4_2:2, level4_3:3, level4_4:4 },
level3_2: { level4_a:1, level4_b:2, level4_c:3, level4_d:4 }
},
level2_2: {
level3_1: { level4_5:1, level4_6:2, level4_7:3, level4_8:4 },
level3_2: { level4_e:1, level4_f:2, level4_g:3, level4_h:4 }
}
}
};
function getUpdatedObject (obj = {}, path = [], newVal) {
const targetLevel = path.length;
return (function setValuesOfPath (obj, path, newVal, currentLevel = 1) {
if(currentLevel === targetLevel && path.length === 1) {
const target = obj[path[0]];
if(target) Object.keys(target).forEach(key => target[key] = newVal);
}
for (var property in obj) {
if (obj.hasOwnProperty(property)) {
if (typeof obj[property] === "object") {
if(property === path[0]) path.shift();
setValuesOfPath(obj[property], path, newVal, currentLevel+1);
}
}
}
return obj
}(obj, path, newVal));
}
console.log(getUpdatedObject(Obj, ["level1_5", "level2_1", "level3_1"], "a"));