Object

Creating Object

				
					//Creating Object
//3 ways
//!1 {}
//!Object.create
//!new Object()

let obj1 = {};
let obj2 = Object.create(Object.prototype);
let obj3 = new Object();

//Assigning 1st way
obj1.name = "Anurag";
console.log(obj1.name); //Anurag

//Assigning 2nd way
obj1["empId"] = "51403607";
console.log(obj1["empId"]); //51403607

//Assigning 3rd way
let job = "job";
obj1[job] = "Software Engineering Manager";
console.log(obj1[job]); //Software Engineering Manager

//Assigning function
obj1.titleFunc = function () {
  return this.name + " with EmpId " + this.empId + " working as " + this.job;
};

console.log(obj1.titleFunc()); //Anurag with EmpId 51403607 working as Software Eng Manager

				
			

Inheritence using object.create()

				
					//Inheritance using Object.create
let inhertitedObject = Object.create(obj1);
Object.defineProperty(inhertitedObject, "titleFunc", {
  value: function () {
    return this.name + " resigned from job";
  },
  writable: false,
  enumerable: false,
  configurable: false,
});
console.log(inhertitedObject.titleFunc());
				
			

Adding dynamic property to object

				
					//Adding dynamic property to object
const ageProperty = "age";
const employee = {
  [ageProperty]: 21,
};
//{age: 21}
console.log(employee);
				
			

Adding dynamic property with spaces in it - First Name

				
					//Add property with spaces
//Add :-  First Name
const ageProperty = "age";
const employee = {
  [ageProperty]: 21,
};
employee["First Name"] = "Rohan Nayak";
console.log(employee["First Name"]);
				
			

Iterate property in Object

				
					//Iterate the object
const employee = {
  name: "Sanjay",
  age: 24,
  Gender: "Male",
};
for (let prop in employee) {
  console.log(prop); //name age gender
}
				
			

Error:- Employee is not iterable-(for of)

				
					//error employee is not iterable
for (let prop of employee) {
  console.log(prop); 
}
				
			

Iterate values in Object

				
					const employee = {
  name: "Sanjay",
  age: 24,
  Gender: "Male",
};

for (let prop in employee) {
  console.log(employee[prop]); //Sanjay 24 Male
}

//key is --> name age gender
for (let key of Object.keys(employee)) {
  console.log(employee[key]); //Sanjay 24 Male
}

				
			

Leave a Comment