Objects and object literals

Object Literals

Basically key-value pairs.

const person = {
	firstName: "John",
	lastName: "Smith",
	age: 30,
	hobbies: ["Piano", "computers", "fruits"],
	address: {
		street: "Main",
		city: "Vancouver",
		number: 30
	}
}
 
person.email = "john@email.com"
 
console.log(person.firstName, person.address.street, person.hobbies[2], person.email)
 
// Access can only be done Python-like
console.log(person["lastName"]);
const item = "lastName";
console.log(person[item]);

Note

Unlike Python, the key does not have to be a string or a defined variable

Note

An object literal can have other objects inside of it

We can also “de-structure” an object literal, meaning we assign variables after the fact to the values in an array.

const {firstName, lastName} = person;
console.log(firstName); // Returns John

Info

For nested object literals, we can do the following:

const {firstName, lastName, address: {city }} = person
// Returns Vancouver

Object literals can also be converted to JSON (for example to send to a server) by using JSON.stringify(<var>) method;

const todos = [
	{
		id:1,
		text: "take out trash",
		isCompleted: true
	},
	{
		id:2,
		text: "meeting",
		isCompleted: true
	},
	{
		id:3,
		text: "sleep",
		isCompleted: false
	},
];
 
 
console.log(todos[0].text)
const todoJSON = JSON.stringify(todos);
console.log(todoJSON)

Objects

To create properties of an object we create a construction function and then use the keyword this to assign those properties. To add a method to an object we again use the this keyword, but we assign it to a function:

// A constructor function
function Person(firstName, lastName, dob) {
    this.firstName = firstName;
    this.lastName = lastName;
    this.dob = new Date(dob); // Using a constructor to create a date class
 
	// Adding methods
	this.getBirthYear = function() {
		return this.dob.getFullYear() // Using the Date method
	}
	this.getFullName = function() {
		return `${this.firstName} ${this.lastName}`
	}
}

To create an instance of this object we must use the new keyword:

const person1 = new Person("John", "Smith", "4-3-1980")

Object prototypes

When creating an object and adding methods as above, any use of console.log on the object will include the methods we wrote, since they are nothing more than other attributes of that object itself.

For readability and better access control, we can add the functionality we require to the __proto__ (or prototype of the constructor “class”) constructor that each function has:

// Assuming the existence of a function Person object...
Person.prototype.getBirthYear = function () {
	return this.dob.getFullYear();
}