Answers for "javascript objects cheat sheet"

0

javascript objects cheat sheet

// Lets define a global obj
const obj = {
	data1: "Hello",
  	data2: "World"
}

/* 
	#Naming keys

	* Every key must be unique
    * It is not necessary that key must hv a value, it can be undefined
*/


// Accessing Keys

	// Defined keys
	console.log(obj.data1) // prints `Hello`

	// Undefined keys (keys which dont exists or dont hv any value)
	console.log(obj.data3) // prints `undefined`

	// Dynamic keys
	let keyString = "data2"
    console.log(obj[keyString]) // prints `World`

// Updating keys
	
	// Defined or undefined key, if key is undefined, it will create new key with that name
	obj.data1 = "Hi" // new value will be hi
	obj.data3 = "Object"

// Deleting keys

	delete obj.data1 // Deletes data1 key, data1 key will have undefined value

// Get list of keys in object
Object.keys(obj) // returns ['data1', 'data2']

// Get list of values from object
Object.values(obj) // returns ['Hello', 'World']

// Get array of values and keys from object
Object.entries(obj) // return [['data1', 'Hello'], ['data2', 'World']]

// Make an object unupdatable
Object.freeze(obj) // after running this you cannot update any key for this object

// Check if object is empty
if(Object.values(obj).length == 0) { /* Object is empty */ }

// Check if object key is available
if(obj.data1) { /* It is available */ }

// Check if dynamic key is available on object
let dynamicKey = "data2"
if(obj[dynamicKey]) { /* Key is available */ }

// Adding functions in object
obj.myFunc = () => { console.log('Hello world') } // Executable by running obj.myFunc()

// OR

obj = {
	myFunc: () => { console.log('Hello world') }
}

// Executable in same way

// using `this keyword` in object
obj.myFunc = () => { console.log(`${this.data1} ${this.data2}`) } // prints `Hello World`, this.data1 = "Hello", this.data2 = "World"
Posted by: Guest on August-17-2021

Code answers related to "Javascript"

Browse Popular Code Answers by Language