Home > front end >  How do I create an array dynamically?
How do I create an array dynamically?

Time:05-01

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';

CodePudding user response:

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.

CodePudding user response:

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);

  • Related