If I have an array describing the path to an object property, e.g ['user', 'personal_info', 'age] and I want to set an object's property according to it, say myObject.user.personal_info.age = 30, how would I do that?
1 Answer
Loop through the keys in the array and use them to access the object properties as though it were a dictionary. (Skip the last key because you need it to access the final property.)
function updatePersonAge(person) {
let keys = ['user', 'personal_info', 'age'];
let obj = person;
for (let i = 0; i < keys.length - 1; i++) {
obj = obj[keys[i]]; // user, personal_info
}
obj[keys[keys.length - 1]] = 30; // age
}
let person = { user: { personal_info: { age: 10 }}};
updatePersonAge(person);
console.log(person);
_.setand Ramdaset