Javascript Objects Literals

  • uses {}
  • stores data in key-value pairs
    • keys are usually without quotes, though they can have them
  • the keys are called properties
  • unlike arrays, objects have no order
  • example:
    let person = {
      name: 'Travis',
      age: 21,
      city: 'LA'
    };
  • can hold all sorts of data
    • example:
      let junkObject = {
        age: 57,
        color: 'purple',
        isHungry: true,
        friends: ['Horatio', 'Hamlet'],
        pet: {
        name: 'Rusty',
        species: 'dog',
        age: 2
        }
      };

Declaring and Initializing

  • declare empty objects: let objectName = {}, let objectName = new Object()
  • new Object syntax:
    let objectName = new Object;
    objectName.key1 = value1;
    objectName.key2 = value2;
    objectName['key3'] = value13;
  • object literal:
    let objectName = {
      key1: value1,
      key2: value2,
      key3: value3
    };

Retrieving Data

  • to retrieve data you have two options:
    • bracket notation --- objectName['key'] --- key must be input as a string
      • example: person['name']
      • similar to arrays but with a string key instead of an index number
      • you can look things up using a variable
        • example:
          let str = 'name';
          someObject[str]
      • can put expressions in the brackets
        • example:
          const nameKey = 'Name';
          jonas['first' + nameKey]
          jonas['last' + nameKey]
    • dot notation --- objectName.key
      • example: person.name
      • must use the real, final property name that appears in the object --- not a calculated property name
      • can't use this notation if the key starts with a number
      • can't use if key has a space in it
      • can't use a variable for the key like with bracket notation (no person.str)

Updating Data

  • access a property and reassign it
  • examples:
    • person['age'] += 1
    • person.city = 'London'

Creating/Initializing Objects

  • make an empty object and then add to it
    • let person = {};
      person.name = 'Travis';
      person.age = 21;
      person.city = 'LA';
  • all at once --- called object literal notation
    • example:
      let person = {
        name: 'Travis',
        age: 21,
        city: 'LA'
      };
  • another way to make an empty object and then add too it
    • let person = new Object();
      person.name = 'Travis';
      person.age = 21;
      person.city = 'LA';

Comparison with Arrays

  • Arrays Objects
    - list of elements - no specific order
    - specific order - use key-value pairs
    - every item is bound to an index - sometimes called dictionaries in other languages
    - items referenced by index (e.g. Python calls them dictionaries)
    - [] - {}
    - access elements by index - access pairs by key with bracket or dot notation
    - use push to add - objectName.key = value to add
    - arrayName[index] = newInfo to reassign - objectName.key = newValue to reassign
  • can think of arrays as a special type of object where the keys are always numbers and they're always in order
    • actually is an object behind the scene

Nested Arrays and Objects

  • can have arrays in objects or objects in arrays
  • example:
    let posts = [
      {
        title: 'Cats are mediocre',
        author: 'Colt',
        comments:['Awesome post', 'terrible post']
      },
      {
        title: 'Cats are actually awesome',
        author: 'Cat Luvr',
        comments: ['<3', 'Go to hell I hate you']
      } 
    ]
    • to access the second comment of the second post - posts[1].comments[1]

Adding Methods to Objects

  • a method is a function that is a property in an object
  • it will be a value (=> it will have a key)
  • the value method is written as an anonymous function
  • call with objectName.key(arguments to pass to value method)
  • methods help keep code organized and grouped logically together vs. writing all the functions separately outside the object
  • methods in objects help avoid namespace collisions --- can have functions named the same thing and they don't conflict because they are stored in different objects
    • example: could have two delete functions - blogPost.delete and comment.delete
  • example:
    let john = {
      firstName: 'John',
      lastName: 'Smith',
      birthYear: 1992,
      family: ['Jane', 'Mark', 'Bob', 'Emily'],
      job: 'teacher',
      isMarried: false,
      calcAge: function() {
          // return 2018 - this.birthYear;     // (A) just returns age, not stored in object
          this.age = 2020 - this.birthYear;    // (B) calculates age and uses 'this.age' save it
                                               // to a new age property in the john object 
      }
    };
    
    // console.log(john.calcAge());    // (A.1) prints the returned age --- could also save it to
                                       // a variable
    // john.age = john.calcAge();      // (A.2) saves returned age to a new 'age' property it
                                       // creates in the john object
    
    john.calcAge();

ES6 Enhancement

  • no longer need to write function or use ; in the method declarations
  • example:
    let john = {
      firstName: 'John',
      lastName: 'Smith',
      birthYear: 1992,
      family: ['Jane', 'Mark', 'Bob', 'Emily'],
      job: 'teacher',
      isMarried: false,
      calcAge() {
          this.age = 2020 - this.birthYear;  
      }
    };

The Keyword this

  • used to access other things in the same object
  • example:
    let comments = {};
    comments.data = ['good job!', 'bye', 'lame...'];
    comments.print = function(){            // don't need an argument because `this` will refer to
      this.data.forEach(function(element){  // the object `comments`  
        console.log(element);              
      })
    }
  • NOTE: for a lot more detail on this see the file notes/javascript/keyword_this.md

Enhanced Object Literals (ES6)

An Object Contained in Another Object

  • in this example we want restaurant to contain operatingHours
const operatingHours = {
  thu: {
    open: 12,
    close: 22,
  },
  fri: {
    open: 11,
    close: 23,
  },
  sat: {
    open: 0,
    close: 24
  },
}

const restaurant = {
  name: 'Classico Italiano',
  location: 'Via Angelo Tavanti 23, Firenze, Italy',
  categories: ['Italian', 'Pizzeria', 'Vegetarian', 'Organic'],
  starterMenu: ['Focaccia', 'Bruschetta', 'Garlic Bread', 'Caprese Salad'],
  mainMenu: ['Pizza', 'Pasta', 'Risotto'],
  order: function (starterIndex, mainIndex) {
    return [this.starterMenu[starterIndex], this.mainMenu[mainIndex]]
  },
// pre ES6:
// operatingHours: operatingHours  

// with ES6:
  operatingHours,
  orderDelivery({
                  starterIndex = 1,
                  mainIndex = 0,
                  time = '20:00',
                  address,
                }) {
    console.log(`Order recieved! ${this.starterMenu[starterIndex]}  and ${this.mainMenu[mainIndex]} will be delivers to ${address} at ${time}`)
  },
  orderPasta(ing1, ing2, ing3) {
    console.log(`Here is your delicious pasta with ${ing1}, ${ing2}, and ${ing3}.`)
  },
  orderPizza(mainIngredient, ...additionalIngredients) {
// just going to log them here, but really you'd do something with the ingredients
    console.log(mainIngredient)
    console.log(additionalIngredients)
  },
}

Compute Property Names

  • want to pull the days from the array into the object
const weekdays = ['mon', 'tues', 'wed', 'thu', 'fri', 'sat', 'sun']

const operatingHours = {
  [weekdays[3]]: {
    open: 12,
    close: 22,
  },
  [weekdays[4]]: {
    open: 11,
    close: 23,
  },
  [`day-${2 + 4}`]: {   // different just to show that you can use other ways to compute property names 
    // as well, not just arrays
    open: 0,
    close: 24
  },
}

Copyright © 2022