Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating an array within an object within an object

Using Javascript, how do I create an array within an object that's within an object, so that my value is stored at: main[1].type[1][0]

I have tried and my code which does not work is as follows:

let main = []

main[1] = {type: {1:['Value1', 'Value2']}, {2:['Value3', 'Value4']}};

console.log(main[1].type[0][1]);

I expect main[1].type[1][0] to be 'Value1' but it is undefined

like image 284
Curiosa Avatar asked Jan 25 '23 23:01

Curiosa


1 Answers

You're not getting undefined. You have a syntax error. A comma should either be separating array values, or separating object entries. You have a comma here, in an object, so it is expected to have a key after it, not a {

main[1] = {type: {1:['Value1', 'Value2']}, {2:['Value3', 'Value4']}};
                                         |
                                         |
                           Remove the } and { around this comma

Remove the } and { around the comma so that {1:['Value1', 'Value2'], 2:['Value3', 'Value4']} becomes a single object with two keys:

const main = [];

main[1] = {type: {1:['Value1', 'Value2'], 2:['Value3', 'Value4']}};

console.log( main[1].type[1][0] );
like image 77
Paul Avatar answered Feb 01 '23 22:02

Paul