Objects

Page section: posts

Objects are collections of variable, arrray or other objects.

Basic syntax:

const climber = {
    name: 'Will Bosi',
    age: 22,
    hardestRoutes: ['King Capella', 'La Capella', 'Furia de Jabali'],
    address: {
        number: 64,
        street: 'Bombay Road',
        town: 'Mumford',
    }
}

NB. Syntax

  1. curlies: = { ... }
  2. key and values seperated by colons
  3. key value pairs separated by commas

You can also suround the keys in quotes but it’s only necessary if the key contains special characters.

Arrays of objects

Basic syntax

const todos = [
    {
        id: 1,
        text: 'Take out rubbish',
        isCompleted: true
    }
    {
        id: 2,
        text: 'Meet with boss',
        isCompleted: true
    }
    {
        id: 3,
        text: 'Dental appointment',
        isCompleted: false
    }
]

Accessing objects

Accessing in the console is easy: console.log(climber) but this won’t work with say an alert. Using alert(climber); just returns [object Object]. You need to loop through climber to list the contents.

Accessing specific part of the object

This is done with dot notation:

console.log(climber.age);

returns the array of routes.

An alternative syntax is alert(climber["hardestRoutes"]) - ie. square brackets and quotation marks.

returns the second in the array of routes

But will again only return [object Object] unless done through the console.

With an array of ojbects like climbers:

const climbers = [
  { climber },
  {
    name: "Adam Ondra",
    age: 30,
    hardestRoutes: ["Change", "Silence", "La Dura Dura", "Vasil Vasil"],
    address: {
      number: 99,
      street: "Greemin Road",
      town: "Kunst Palisky",
    },
  },
];

You can also get a particular character of a string using square bracket notation: