Array inside a JavaScript Object?

Solution 1:

Kill the braces.

var defaults = {
 backgroundcolor: '#000',
 color: '#fff',
 weekdays: ['sun','mon','tue','wed','thu','fri','sat']
};

Solution 2:

// define
var foo = {
  bar: ['foo', 'bar', 'baz']
};

// access
foo.bar[2]; // will give you 'baz'

Solution 3:

var data = {
  name: "Ankit",
  age: 24,
  workingDay: ["Mon", "Tue", "Wed", "Thu", "Fri"]
};

for (const key in data) {
  if (data.hasOwnProperty(key)) {
    const element = data[key];
      console.log(key+": ", element);
  }
}

Solution 4:

If you are so organised you may declare the entire object from the outset (this comma-delimited list is called an object initializer):

const myObject = {
    string:   'Galactic Rainbows',
    color:    'HotPink',
    sociopaths: ["Hitler","Stalin","Gates"]
}

Alternatively, once you have declared the object,

const myObject = {};    // this line is the declaration
    // it is equivalent to:
const myObject2 = new Object();

you may define its properties by giving them values:

myObject.string = "Galactic Rainbows";
myObject.color = "HotPink";
myObject.sociopaths = ["Hitler","Stalin","Gates"];

All examples below assume the object is already declared (as above)

I prefer to declare the array separately, like this, and then assign it to the object:

const weekdays = ['sun','mon','tue','wed','thu','fri','sat'];
myObject.weekdays = weekdays;

But if you have already declared the object, it would be quicker to code:

myObject.weekdays = ['sun','mon','tue','wed','thu','fri','sat'];

But you cannot assign an array of arrays to the object like this:

myObject.girlsAndBoys[0] = ["John","Frank","Tom"];    //Uncaught TypeError: Cannot set property '1' of undefined
myObject.girtsAndBoys[1] = ["Jill","Sarah","Sally"];   //Uncaught TypeError: Cannot set property '1' of undefined

To assign a two dimensional array to an object you have a few options. You can initialise the empty 2D array first:

myObject.girlsAndBoys    = [[]];
myObject.girlsAndBoys[0] = ["John","Frank","Tom"]; 
myObject.girtsAndBoys[1] = ["Jill","Sarah","Sally"];   

Or you may do it layer by layer:

const boys  = ["John","Frank","Tom"];    
const girls = ["Jill","Sarah","Sally"];
myObject.girlsAndBoys = [[boys],[girls]];

Alternatively you may do it all at once (after no more than the object declaration):

const myObject = {};
myObject.girlsAndBoys = [["John","Frank","Tom"],["Jill","Sarah","Sally"]];
myObject.girlsAndBoys[0][0] == "John";   // returns True