'How do I create an array dynamically?

I'd like to create an array like this by code.

let arr = {
    'First': {
        'bg': 'a',
        'fg': 'b'
    },
    'Second': {
        'bg': 'c',
        'fg': 'd'
    }
};

This doesn't work:

Uncaught TypeError: Cannot set properties of undefined (setting 'bg')

var arr = [];
arr['First']['bg'] = 'a';
arr['First']['fg'] = 'b';

arr['Second']['bg'] = 'c';
arr['Second']['fg'] = 'd';


Solution 1:[1]

You have to create intermediate objects before you can create the nested properties.

var arr = {};
arr['First'] = {};
arr['First']['bg'] = 'a';
arr['First']['fg'] = 'b';
arr['Second'] = {};
arr['Second']['bg'] = 'c';
arr['Second']['fg'] = 'd';

And note that you should be using {}, not []. {} is an object, [] is an array.

Solution 2:[2]

This will do the job:

var arr = {};

// Create the "First" 
arr['First'] = {};
arr['First']['bg'] = 'a';
arr['First']['fg'] = 'b';

// Create the "Second"
arr['Second'] = {};
arr['Second']['bg'] = 'c';
arr['Second']['fg'] = 'd';

console.log(arr);

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Barmar
Solution 2