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?
Asked
Active
Viewed 196 times
0

Victor Bittencourt
- 67
- 1
- 6
-
The linked answer deals with accessing the final property value, but it's not an adequate solution for modifying it. – Abion47 Jul 02 '20 at 17:48
-
A more relevant dupe: [How to set object property (of object property of..) given its string name in JavaScript?](https://stackoverflow.com/q/13719593) - it starts with a string but the first step is transforming that string to an array of properties to access. – VLAZ Jul 02 '20 at 17:51
-
Also [Lodash: `_.set`](https://lodash.com/docs/4.17.15#set) and [Ramda `set`](https://ramdajs.com/docs/#set) – VLAZ Jul 02 '20 at 17:53
1 Answers
0
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);

Abion47
- 22,211
- 4
- 65
- 88