Multi level dynamic key setting?

How do you set a multi-level deep update on an object with a dynamic key in javascript? When i try a typical dynamic update, it adds another key/value pair instead of updating the correct parameter.

let home = {
  street: {
    house: {
      room: {
        window: true
      }
    }
  }
}

let update = {
  key: "house.room.window",
  value: "false"
}

home.street[update.key] = update.value;
console.log(home);

expected:

home = {
    street:{
        house: {
            room: {
                window: false
            }
        }
    }
}

instead i get:

home = {
    street:{
        house: {
            room: {
                window: true
            }
        }
        "house.room.window": false
    }
}

2 thoughts on “Multi level dynamic key setting?”

  1. Try like below. Explanation is in comments.

    let home = {
      street: {
        house: {
          room: {
            window: true
          }
        }
      }
    }
    
    let update = {
      key: "house.room.window",
      value: "false"
    }
    
    // select object to get updated
    let obj = home.street;
    // get array of nested keys
    let nestedKeys = update.key.split('.');
    // get object from nested keys until last key
    // used slice(0, -1) so it will iterate through all key except last one
    nestedKeys.slice(0, -1).forEach(k => obj = obj[k]);
    
    // use object with last key and update value
    obj[nestedKeys[nestedKeys.length - 1]] = update.value
    
    // log object
    console.log(home);
    Reply

Leave a Comment