0

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?

3

1 Answer 1

1

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);

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.