OBJECTS
An object is a data type that allows you to store key-value pairs.
var myMonkeyObject = {};
myMonkeyObject.name = "King Kong";
myMonkeyObject.age = 32;
alert(myMonkeyObject.name);
var studentObject = {
name:"Fred",
age: "12",
sneakyFunction: function() {
return "WhatEver";
}
}
Objects
An object can contain complex structured data.
An example of an object
monkey
name
age
The JavaScript code for the above is...
var myMonkeyObject = {}
myMonkeyObject.name = "King Kong"
myMonkeyObject.age = 32;
alert(myMonkeyObject.name);
How many ways to create an object
Object literal
var person = {
name: "Bob",
age: 38,
role: "Trainer"
}
console.log( person )
Object Contructor
var person = new Object()
person.name = "Fred"
person.age = 38
person.role = "Trainer"
console.log(person)
Object.create() method
var person = {
name: "",
age: 0,
role: ""
}
var man = Object.create(person)
man.name = "Ivan"
man.age: 38
man.role = "Trainer"
How to delete a property of an object
var person = {
age: 21
}
delete person.age
How to iterate over the properties of an object
- for ... in loop
- Object.keys() & forEach
- Object.values() & forEach()
// for...in loop
const person = {
name: "John",
age: 30
}
for (let prop in person ) {
console.log( prop + ":" + person[prop])
}
// Object.keys() & forEach()
const keys = Object.keys(person)
keys.forEach( key => {
const value = keys[key]
console.log( `${key} : ${value}` )
} )
// Object.values(whatever) & forEach()
const values = Object.values(person)
values.forEach(val => {
console.log( val )
}
)
How do you check if a property exists in an object
// in
var person = {
name: "Ivan",
age: 25
}
console.log( "name" in person )
// Ouput: true
console.log( "crash" in person )
// Ouput: false
// hasOwnProperty
var person = {
name: "Alice",
age: 25
}
console.log( person.hasOwnProperty("name")
// Output : true
console.log( person.hasOwnProprty("city")
// Ouput : false
// comparing with undefined
console.log( person.name !== undefined )
console.log( person.city != undefined )
How do you clone or copy an object - shallow vs deep copy
// Spread operator
const ob = {
name: "Ivan",
age: 35,
city: "London"
}
// Shallow copy
const clonedObject = {...ob }
// Object.assign()
// shallow copy
const clonedObject = Object.assign({}, ob )
// JSON.parse() & JSON.stringify()
// deep copy
const temp = JSON.stringify(ob)
const clonedObject = JSON.parse(temp)