Home > database >  Set nested dynamic keys over dynamic keys
Set nested dynamic keys over dynamic keys

Time:06-15

Lets say I've got the following:

  let key1 = 'firstkey'
  let key2 = 'secondkey'
  let obj = {}

Now I can set a key on obj using a dynamic key as:

  obj[key1]= 'randomvalue' // Equals to obj: { firstkey: 'randomvalue' } 

there is a quick way of writing this:

  obj[key1][key2] = 'randomvalue' // Should equal to obj: { firstkey: { secondkey: 'randomvalue'} } 

Without needing to previously check if the nested property key1 actually exists?

CodePudding user response:

Option 1, using the spread operator

let key1 = "firstkey";
let key2 = "secondkey";
let obj = {};

obj[key1] = { ...obj[key1], [key2]: "randomvalue" };

Option 2, use Lodash.set

_.set(obj, [key1, key2], "randomvalue");
  • Related