Objects in ES6

Object is a collection keys, values pairs, where key, value separated using colon (:), key is a string and value can be anything (String, number, boolean, etc)

let person={
name:"Rama",
year: 2016,
}

Create empty object

let person={};
or
let person=new Object();

Add propety and value to object

person.name="Rama"
person.age=20

Delete object property

delete person.age

Update object property

person.name="Krishna"

Methods in object

person.details=function(){
console.log("method in object")
}

Shorthand of methods in object

let person={
   name:"Rama",
   age:20,
   details(){
    console.log(`Name: ${this.name}, Age: ${this.age}`);
   }
};

in operator

console.log(name in person)

for-in loop 

for(let key in person){
console.log(person[key])
}

Object copying

"use strict"
let person={
name:"aman",
age:20
}

console.log(person)

let user = person
console.log(user)
user.name="ajay";
console.log(person);

Object Referencing(Cloning)

let human={};
let person={
name:"aman",
age:20
}
 Object.assign(human, person);
human.name="Rama"
console.log(human)
console.log(person)

Constructor

Constructor allow us to create multiple objects from single skelton.

function User(name, age){
this.name= name;
this.age=age;
}
let user1=new User("Aman", 20);
console.log(typeof user1);
let user2=new User("Rakesh", 20);
console.log(typeof user2);

Constructor with return statement

function User(name, age){
this.name=name;
this.age=age;
return {name: this.name};
}
console.log(new User("Aman", 20).name);

Optional chaining (?.)

It provide safe way to access nested properties of an object.

let user={
name:"aman",
age:20,
contacts:{
mobile1: 7579237515,
mobile2: 9557167340
}
}
console.log(user.contacts.mobile1); // 7579237515
console.log(user.address.state); // will throw an error
console.log(user?.address?.state); // undefined

Get array of keys, values, and entries of object

"use strict"
let user={
	name:"aman",
	age:20,
	contacts:{
		mobile1: 7579237515,
		mobile2: 9557167340
	}
}
console.log(Object.keys(user));
console.log(Object.values(user));
console.log(Object.entries(user));

Sharing object data over network

  • JSON.parse(json_string)
    Convert JSON into an object
  • JSON.stringify(object)
    Convert object into JSON string
© 2016 - 2022, All Rights are Reserved.