5:2 Combining arrays and objects

Arrays can contain objects, objects can contain arrays. Its really common to want to use both.

An array of objects

Having an array (or list) of objects is a really common use case. Lets take our breakfast example, what if we had a load of breakfast orders:

let breakfasts = [
  {
    eggs: 2,
    bacon: 3,
    toast: 0
  },
  {
    eggs: 1,
    bacon: 0,
    toast: 1,
  },
  { 
    eggs: 4,
    bacon: 2,
    toast:2
  }
]

Above we make an array with square brackets and separate each object with a comma.

Arrays within an object

Its perfectly fine to have arrays within an object (more or less anything can be stored in an object.

let meal = {
  customers: 3,
  names: ["sally", "dave", "jane"]
}

Using arrays of objects in generative art

A really useful thing to do in generative art is store the locations of a lot of different things. You might have 100 circles and want to keep track of their x and y positions:

let objectsArray = [
  {
    x: 10,
    y: 12
  },
  {
    x: 100,
    y: 200
  },
  {
    x: 44,
    y: 33
  }
  // and so on....
]

This might be an object that is updated as things move, you can iterate over the object in a loop to draw shapes. Have a look at the example here.

Adding objects to an array and drawing them

Using objects and arrays to store things is very useful if you want to animate, or change values.

In the example here we add shapes to an array with push() this addes a value to the end of the array. Each time we do this we store an object with x and y in the array. The draw function automatically then adds the shapes.

Animate and manipulate objects and arrays

Once you've got objects in arrays it is very easy to manipulate them. In this example each object is a separate particle that we can observe and control in a really simple way.

Using mousePressed() instead of mousePressed() we can add lots at once. When we loop through the array to draw the circles we can also change a value. Gravity is simulated by multiplying the y value by a variable.