How do I declare an array of objects?

Hello,

I’m struggling with the definition of an array with the following (nested) structure - refer to picture:

For each item in phase[] there should be:

  • a title (string)
  • a subtitle (string)
  • an array of milestone [] (each a string)
  • an array of engagement [] (each consisting of the following:)
    • a name (string)
    • a purpose (string)
    • a deliverable (string)

As an example, I’d like to access the variable phase[1].engagement[1].deliverable to get the value of the deliverable of engagement[1] of phase[1].
Or phase[0].subtitle should be the subtitle of phase[0].

Would anyone kindly be able to help?

Thanks!

Each index in phase[] is an object w/ many properties.

And 1 of them is another array named engagement[] containing 2 objects w/ many properties too.

In order to facilitate the creation of those 2 sets of object properties we can define a different class for each of both:

Starting w/ the inner engagements[] we can define an Engagement class w/ its constructor() accepting the following parameters: (name, purpose, deliverable):

class Engagement {
  constructor(name, purpose, deliverable) {
    this.name = name;
    this.purpose = purpose;
    this.deliverable = deliverable;
  }
}

We do the same for the phases[] array, defining a class named Phase:

class Phase {
  constructor(title, subtitle, milestones, engagements) {
    this.title = title;
    this.subtitle = subtitle;
    this.milestones = milestones;
    this.engagements = engagements;
  }
}

Now we declare the array variables we’re gonna need to store the instances of those 2 classes:

const PHASES = 2, phases = Array(PHASES).fill();
var engagements;

Before instantiating our 2 Phase objects we 1st need to instantiate an Engagement using the keyword new twice passing the required arguments for its constructor() and storing them in the engagements[] array:

engagements = [
  new Engagement('Wilson', 'marry', true),
  new Engagement('Sarrah', 'marry', true)
];

After that we can instantiate our 1st Phase and store it in the 1st index of phases[]:

phases[0] = new Phase('Happy Forever!', 'Engaged', [], engagements);
console.table(engagements);

We repeat the steps again for the 2nd index of phases[]:

engagements = [
  new Engagement('John', 'travel', false),
  new Engagement('Mary', 'travel', false)
];

phases[1] = new Phase('Savannah Adventures', 'Wilderness', [], engagements);
console.table(engagements);

console.table(phases);

Now we can further inspect the contents of the phases[] array like this:

console.log(phases[1].engagements[1].deliverable);
console.log(phases[0].subtitle);
3 Likes

Thank you very much, GoToLoop, for the comprehensive reply. I’ll have to digest it first and try around a little before I can even properly appreciate your kind reply.