1// Lets define a global obj
2const obj = {
3 data1: "Hello",
4 data2: "World"
5}
6
7/*
8 #Naming keys
9
10 * Every key must be unique
11 * It is not necessary that key must hv a value, it can be undefined
12*/
13
14
15// Accessing Keys
16
17 // Defined keys
18 console.log(obj.data1) // prints `Hello`
19
20 // Undefined keys (keys which dont exists or dont hv any value)
21 console.log(obj.data3) // prints `undefined`
22
23 // Dynamic keys
24 let keyString = "data2"
25 console.log(obj[keyString]) // prints `World`
26
27// Updating keys
28
29 // Defined or undefined key, if key is undefined, it will create new key with that name
30 obj.data1 = "Hi" // new value will be hi
31 obj.data3 = "Object"
32
33// Deleting keys
34
35 delete obj.data1 // Deletes data1 key, data1 key will have undefined value
36
37// Get list of keys in object
38Object.keys(obj) // returns ['data1', 'data2']
39
40// Get list of values from object
41Object.values(obj) // returns ['Hello', 'World']
42
43// Get array of values and keys from object
44Object.entries(obj) // return [['data1', 'Hello'], ['data2', 'World']]
45
46// Make an object unupdatable
47Object.freeze(obj) // after running this you cannot update any key for this object
48
49// Check if object is empty
50if(Object.values(obj).length == 0) { /* Object is empty */ }
51
52// Check if object key is available
53if(obj.data1) { /* It is available */ }
54
55// Check if dynamic key is available on object
56let dynamicKey = "data2"
57if(obj[dynamicKey]) { /* Key is available */ }
58
59// Adding functions in object
60obj.myFunc = () => { console.log('Hello world') } // Executable by running obj.myFunc()
61
62// OR
63
64obj = {
65 myFunc: () => { console.log('Hello world') }
66}
67
68// Executable in same way
69
70// using `this keyword` in object
71obj.myFunc = () => { console.log(`${this.data1} ${this.data2}`) } // prints `Hello World`, this.data1 = "Hello", this.data2 = "World"
72