Object Declaration:
An empty object (empty cabinet) can be created using one of two syntaxes:
let user = new Object(); // “object constructor” syntax
let user = {}; // “object literal” syntax
Object With Constructor:
Accessing Object Properties:
Get Values from an Object : Object.values()
Get Keys from an Object : Object.keys()
Object To Array Entries : Object.entries()
Merging Object with Spread:
Combining Two Object : Object.assign()
Freezing An Object : Object.freeze()
Object Frozen or Not : Object.isFrozen()
Sealing an Object : Object.seal()
Object Sealed or Not : Object.isSealed()
Localization : Object.toLocaleString()
JSON Irteration – Recurssion
Object With Constructor:
We can create an object with these two steps:
- Define the object type by writing a constructor function. There is a strong convention, with good reason, to use a capital initial letter.
- Create an instance of the object with new.
function User(name, age, mobile) {
this.name = name;
this.age = age;
this.mobile = mobile;
}
var user1 = new User('Talha', 26, 8801967402131);
console.log(user1)
//
user1 = {
age: 26,
mobile: 1993,
name: "Talha"
}
Dynamic Object
var key = 'DYNAMIC_KEY',
obj = {
[key]: 'ES6!'
};
console.log(obj);
// > { 'DYNAMIC_KEY': 'ES6!' }
Link 01
Example 2
let sort_qry = { $sort: {} };
sort_qry.$sort ["staff."+ args.sortBy.toLowerCase()] = -1
//Output:
sort_qry : { '$sort': { 'staff.name': 1 } }
2.
let updateObj = { $set: {} };
for (var param in args.set) {
updateObj.$set[param] = args.set[param];
}
Basically, the syntax is:
obj[variable] = value;
Variable must contain a primitive value.
const firstGrandfathersChildren = obj.firstGrandFather.children
Accessing Object Properties:
We can access object properties in two different ways. One of them is bracket notation.
object[key]
and the other one is the dot notation.
object.key
const user = {
name: "Talha",
age: 26,
marks: {
math: 20,
eng:30
}
};
console.log(user["marks"]["math"]) //20
console.log(user.marks.math) //20
Get Values from an Object : Object.values()
Return an array of the values of an object.
const user1 = {
age: 26,
mobile: 8801967402131,
name: "Talha"
}
const user = Object.values(user1);
console.log(user) //[26, 8801967402131, "Talha"]
Get Keys from an Object : Object.keys()
Return an array of the keys of an object.
const user1 = {
age: 26,
mobile: 8801967402131,
name: "Talha"
}
const user = Object.keys(user1);
console.log(user) //["age", "mobile", "name"]
Object To Array Entries : Object.entries()
Creates an array which contains arrays of key/value pairs of an object.
const user1 = {
age: 26,
mobile: 8801967402131,
name: "Talha"
}
const user = Object.entries(user1);
console.log(user)
//[["age", 26], ["mobile", 8801967402131], ["name", "Talha"]]
Merging Object with Spread:
Merging two objects and that returns a new object.
const user1 = {
age: 26,
mobile: 8801967402131,
name: "Talha"
}
const newObj = {
...user1,
location: 'sylhet'
}
console.log(newObj)
//
newObj = {
age: 26,
location: "Dhaka",
mobile: 8801967402131,
name: "Talha"
}
Combining Two Object : Object.assign()
Similar to the spread operator. Allows for objects to be combined together.
const user1 = {
birtYear: 1993,
name: "Talha"
}
const user1NewVal = {
age: 26,
}
const combineObj = Object.assign(user1, user1NewVal)
console.log(combineObj)
//
{
age: 26,
birtYear: 1993,
name: "Talha"
}
Freezing An Object : Object.freeze()
Prevents from modifying existing properties or adding new properties and values in the object. It’s often what people think const does, however const allows you to modify an object.
const user1 = {
age: 26,
mobile: 1993,
name: "Talha"
}
Object.freeze(user1);
user1.name = 'Abu';
console.log(user1.name) //"Talha"
Object Frozen or Not : Object.isFrozen()
The Object.isFrozen() determines if an object is frozen. Return Bolean value.
const user1 = {
age: 26,
mobile: 1993,
name: "Talha"
}
console.log(Object.isFrozen(user1)) // false
Object.freeze(user1)
console.log(Object.isFrozen(user1)) // ture
Sealing an Object : Object.seal()
The method seals an object, preventing new properties from being added to it and marking all existing properties as non-configurable. Values of present properties can still be changed as long as they are writable.
const user1 = {
mobile: 1993,
name: "Talha"
}
Object.seal(user1);
user1.age = 'ABU';
console.log(user1.name) //"ABU"
user1.age = 26;
console.log(user1.age) //undefined
In the above example, we can see that user1 objects value of existing key can be changeable but we can not delete or insert new properties in this object.
Object Sealed or Not : Object.isSealed()
The Object.isSealed() method determines if an object is sealed.
const user1 = {
mobile: 1993,
name: "Talha"
}
console.log(Object.isSealed(user1)) //false
Object.seal(user1);
console.log(Object.isSealed(user1)) // ture
Localization : Object.toLocaleString()
The method returns a string representing the object. This method is meant to be overridden by derived objects for locale-specific purposes.
const date1 = new Date(Date.UTC(2018, 11, 20, 3, 0, 0));
console.log(date1.toLocaleString('bn'))
//"৫/১২/২০১৮ ৯:০০:০০ AM"
JSON Irteration – Recurssion :
let data = {
id: 1,
name: "abc",
address: {
streetName: "cde",
streetId: 2
}
};
function traverse_it(obj) {
for (var prop in obj) {
if (typeof obj[prop] == "object") {
// object
traverse_it(obj[prop]);
} else {
// something else
console.log("The value of " + prop + " is " + obj[prop] + ".");
}
}
}
traverse_it(data);
How to access nested JSON data
Object Clone Secrets
1. Here “z” property will not display
//Object clone secrets
//copy/deep clone an Object
//1. JSON.parse, JSON.stringify
//2. Object.assign
let obj = {x: 1, y:2, z: function(){}}
let obj1 = JSON.parse(JSON.stringify(obj))
obj1.x = 10;
console.log(obj)
console.log(obj1)
2. “NaN” will create “NULL” value
let obj = {x: 1, y:2, z: NaN }
let obj1 = JSON.parse(JSON.stringify(obj))
obj1.x = 10;
console.log(obj)
console.log(obj1)
Parse,Stringify are slow perform, time taking process. The another way we can use is “Object.assign”
II. Object.assign is better approach, but it has some drawbacks
let obj = {x: 1, y:2 , t: NaN}
let obj1 = Object.assign({}, obj, {w:1})
obj1.x = 10;
console.log(obj)
console.log(obj1)
b. Both will have the same innerObj value, bcz obj will have the reference of the inneer object
let obj = {
x: 1,
y: 2,
t: {innerObj: 1}
};
let obj1 = Object.assign({}, obj, { w: 1 });
obj1.z.innerObj = 10;
console.log(obj);
console.log(obj1);
Solution : use underscore library => _.deepClone method
Reference
Javascript-array-and-object-methods
javascript-object-manipulation
all-about-immutable-arrays-and-objects-in-javascript
Understanding the JavaScript Spread Operator