Last active
September 10, 2022 04:50
-
-
Save joe-oli/5f883faafcb85e8739c238d013554dbd to your computer and use it in GitHub Desktop.
Javascript tips
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//#1. for . . . in | |
//By looping through the keys, you can get the value using object[key] | |
const object = { | |
name: "Cindi", | |
language:"js" | |
} | |
for(const key in object){ | |
const value = object[key] | |
console.log("Key: ",key) | |
console.log("Value: ",value) | |
} | |
// Key: name | |
// Value: Cindi | |
// Key: language | |
// Value: js | |
/* | |
#2 Object.keys() | |
================= | |
The keys method of the Object constructor returns an array of the keys in an object; | |
With the array of keys you can then loop through the array using any array approaches; | |
You can get the value fo the objects key also using object[key] | |
*/ | |
const object = { | |
name: "Cindi", | |
language:"js" | |
} | |
const keys = Object.keys(object) | |
// ['name', 'language'] | |
keys.forEach(function(key){ | |
const value = object[key] | |
console.log("Key: ",key) | |
console.log("Value: ",value) | |
}) | |
// Key: name | |
// Value: Cindi | |
// Key: language | |
// Value: js | |
/* #3. Object.values() | |
===================== | |
The values method returns an array of the values in an object ( opposite to keys method ) | |
With the array got you can loop through them using any array functionality | |
You can use a key to get a value directly but you cannot use a value to get a key directly | |
*/ | |
const object = { | |
name: "Cindi", | |
language:"js" | |
} | |
const values = Object.values(object) | |
// ['Dhanush', 'js'] | |
values.forEach(function(value){ | |
console.log(value) | |
}) | |
// Cindi | |
// js | |
/* #4. Object.entries() | |
======================== | |
The entries method returns an array of subarrays where each subarray has two items, the first one being the key and the second one being the value | |
Unlike the keys and values method, entries returns the keys and values of an object in subarrays. | |
Then you can access them using the index. | |
*/ | |
const object = { | |
name: "Cindi", | |
language:"js" | |
} | |
const entries = Object.entries(object)Looping through objects in javascript | |
// [ | |
// ['name', 'Cindi'], | |
// ['language', 'js'], | |
// ] | |
entries.forEach(function(entry){ | |
const key = entry[0] | |
const value = entry[1] | |
console.log("Key: ",key) | |
console.log("Value: ",value) | |
console.log(value) | |
}) | |
// Key: name | |
// Value: Cindi | |
// Key: language | |
// Value: js |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment