Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set nested object with dynamic keys on javascript

Tags:

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
like image 691
Edgaras Karka Avatar asked Sep 19 '25 07:09

Edgaras Karka


1 Answers

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.

like image 171
Barmar Avatar answered Sep 21 '25 00:09

Barmar