Object Basics
1. An Object is a block of memory which has state (variables), behavior (methods) and where we can store heterogeneous data.
2. An object is a collection of key-value pairs that can contain various data types, such as numbers, strings, arrays, functions, and other objects.
3. In one object we can have multiple key-value pairs and they should be separated by ',' comma.
4. We can access value of object using (.) Operator or square bracket [ ], object reference and key_name.
Object Keys (Properties)
1. Object key (property) will be automatically converted into string by JS engine.
2. If keys name are in Number, JS engine will convert them into string and arrange them in ascending order.
3. To write space separated key names, we have to enclose key name with double quotes.
4. If we want to give computed or user defined property then we have to use square brackets and variable name.
5. If key-name is same as variable name which hold the value, instead of writing two times we can write variable name only once.
let phone = 8800425635;
let obj = {
phone,
// phone:phone
};
Ways to Create Object
1. By using curly braces { } and literals
let obj = {}
// empty object
let obj = { name:"chombi", age:16 }
// object with literals
2. By using new keyword and Constructor
let obj = new Object();
// {} empty object
let obj = new Object({ name:"chombi" });
// { name:"chombi" } object with literals
3. By using new keyword and Constructor function.
4. By using class
Access Object Values
1. By using dot operator (.) and key name
let obj = { name:"chombi", age:16 }
console.log(obj.name) // chombi
console.log(obj.age) // 16
2. By using square brackets ([]) and key name
let obj = { name:"chombi", age:16 }
console.log(obj["name"]) // chombi
console.log(obj["age"]) // 16
3. If we try to access property which is not available in object we will get undefined.
Object Methods
1. In JavaScript, object methods are functions that are attached to the object, and can be called on that object reference.
2. To call a function, we use square brackets instead dot operator.
3. Here, speak is a variable which holds the function reference.
let obj1 = {
name: "chombi",
age: 16,
speak: function() {
console.log('i can speak');
}
}
console.log(obj1["speak"]());
// i can speak
4. Access object property inside function - function declared with function keyword
let obj1 = {
name: "chombi",
age: 16,
speak: function() {
console.log('My name is ' + this.name + ', age ' + this.age + ' and i can speak');
}
}
console.log(obj1["speak"]());
// My name is chombi, age 16 and i can speak
Here, we can access object property, by using 'this' keyword.
5. Access object property inside function - Arrow function
let obj1 = {
name: "chombi",
age: 16,
speak: () => {
console.log("My name is " + obj1.name + ", age " + obj1.age + " and i can speak");
}
};
console.log(obj1["speak"]());
// My name is chombi, age 16 and i can speak
Here, we can access object property, by using object reference because arrow function is not having 'this' property.
Add Key-Value in Object
1. To add key-value pair we can using dot operator and square brackets
2. By using dot operator (.) and key name
let obj = { name:"chombi", age:16 }
obj.country = "india";
// new key-value added in object
// {
// name:"chombi",
// age:16,
// country:"india",
// }
Example:
let obj = { name:"chombi", age:16 }
obj.age = 18;
// age property value is updated
// {
// name:"chombi",
// age:18,
// }
Check Property is Available in Object or Not
1. We can check using "in" operator.
Syntax: "property name" in object_name
let obj = { name:"chombi", age:16 }
console.log("name" in obj) // true
console.log("age" in obj) // true
console.log("city" in obj) // false
Copy of Object
1. We can create copy of two types:
- Shallow copy
- Deep Copy
Shallow Copy
1. The copy of object that is directly connected with original object is called as shallow object.
2. Here, we store reference of original object in a new variable, now new variable starts pointing to same memory block.
3. So if we make any changes in copy, it will be reflected to original object because both variables are pointing to same memory block.
let obj = { name:"chombi", age:16 }
let obj_cpy = obj;
// reference of obj is copied in obj_cpy
obj_copy.age = 20;
console.log(obj_copy);
// { name:"chombi", age:20 }
console.log(obj);
// { name:"chombi", age:20 }
Deep Copy
1. The copy in which original object is not connected with its copy, is called as Deep copy.
2. Here, we create separate empty object and after that we copy key-value pair of original object into new empty object.
3. Now, if we make any changes in copy, it will not be reflected to original object because we have create separate memory blocks.
4. Create copy using for loop
let obj1 = { name:"chombi", age:16 }
let obj2 = { }
// new empty object
for (prop in obj1) {
obj2[prop] = obj1[prop]
console.log(obj2)
}
// copy key-values into new object
obj2.age = 20;
console.log(obj2);
// { name:"chombi", age:20 }
console.log(obj1);
// { name:"chombi", age:16 }
Object In-built Methods
1. Object.keys(obj_ref)
1. Returns an array of given object's property names.
const obj = { a: 1, b: 2, c: 3 };
console.log(Object.keys(obj));
// Output: ["a", "b", "c"]
2. Object.values(obj_ref)
1. Returns an array of given object's values.
const obj = { a: 1, b: 2, c: 3 };
console.log(Object.values(obj));
// Output: [1, 2, 3]
3. Object.entries(obj_ref)
1. Returns an array of key-value pairs in an array.
const obj = { a: 1, b: 2, c: 3 };
console.log(Object.entries(obj));
// Output: [["a",1], ["b",2], ["c",3]]
4. Object.assign(target_obj, src1, ..., srcn)
1. Copies key-value pair from one or more source objects to a target object.
const target = { a: 1, b: 2 };
const source = { c: 4, d: 5 };
const result = Object.assign(target, source);
console.log(result);
// Output: { a: 1, b: 2, c: 4, d: 5 }