简体   繁体   中英

How to set nested object with dynamic keys on javascript

let foo = {};

const key1 = 'a';
const key2 = 'b';
const key3 = 'c';

foo[key1][key2][key3] = [1, 2];

When I trying to do something similar I get:

Uncaught TypeError: Cannot read property 'b' of undefined

You have to create the nested object before you can create a property in it.

 let foo = {} const key1 = 'a' const key2 = 'b' const key3 = 'c' foo[key1] = {}; foo[key1][key2] = {}; foo[key1][key2][key3] = [1, 2]; console.log(foo); 

If the list of keys is generated dynamically in an array, see Populate nested object from array? for a function to create all the objects.

You can also create the literal object with dynamic keys. Just make sure to create nested objects where necessary as @Barmar demonstrated.

 const key1 = 'a' const key2 = 'b' const key3 = 'c' let foo = { [key1]: { [key2]: { [key3]: [1, 2] } } }; console.log(foo.abc); 

You can create a function which takes three parameters:

  • The object on which keys will be added.
  • The array of keys in order.
  • The value which will be set to the last level.

Use forEach loop to loop though the keys. Except for last index add empty {} to the key. And change the current object to that empty object.

 let foo = {} function nestedKey(obj,keys,value){ keys.forEach((x,i) => { obj[x] = i === keys.length -1 ? value : {}; obj = obj[x] }) } nestedKey(foo,['a','b','c'],[1,2]); console.log(foo) 

Using Array#reduce will make this possible, however the keys need to be in a list and in reverse order.

 const key1 = 'a' const key2 = 'b' const key3 = 'c' const foo = [key3, key2, key1].reduce((a,c)=>({[c]:a}), [1, 2]); console.log(foo); 

Try (improved Barmar answer without keys repetition)

 let foo = {}, t; const key1 = 'a'; const key2 = 'b'; const key3 = 'c'; t= foo[key1]= {}; t= t[key2]= {}; t[key3]= [1, 2]; console.log(foo); 
If foo has more (nested) values they will be saved

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM