I have an array of unknown length which defines the path to content I want to alter in a object.
This is what I want.
let updatedContent = "Hello World!";
let myArray = ["layer1","layer2","layer3"];
myObject["layer1"]["layer2"]["layer3"] = updatedContent;
My problem is myArray is of unknown length. What is the best way to update a value in the object?
CodePudding user response:
Here's an ugly approach using a recursive function. The idea is retrieving the nested properties in sequence, calling the function recursivelly with the current level, until the end of the array:
function changeObject(obj, arr, content, index = 0) {
if (index < arr.length - 1) {
changeObject(obj[arr[index]], arr, content, index);
} else {
obj[arr[index]] = content;
}
};
const myObject = {
layer1: {
layer2: {
layer3: "foo"
}
}
};
let updatedContent = "Hello World!";
let myArray = ["layer1", "layer2", "layer3"];
myObject["layer1"]["layer2"]["layer3"] = updatedContent;
changeObject(myObject, myArray, updatedContent);
console.log(myObject);