An Interest In:
Web News this Week
- April 27, 2024
- April 26, 2024
- April 25, 2024
- April 24, 2024
- April 23, 2024
- April 22, 2024
- April 21, 2024
May 21, 2022 08:44 am GMT
Original Link: https://dev.to/naimahmedshuvo/how-to-loop-over-an-object-in-javascript-15pj
How To Loop Over An Object In Javascript
1. Use Object.keys to get an array of keys of the object and loop over it.
let myObj = { name: 'Shuvo', tech: 'javascript', hobby: 'learning javascript', favFood: 'beef steak!',};// way: 1 Object.keys(myObj).map((key) => { console.log(`key: ${key} value: ${myObj[key]}`); });// output// key: name value: Shuvo// key: tech value: javascript// key: hobby value: learning javascript// key: favFood value: beef steak!
2. Use For...in Loop to over the object.
// way: 2for (key in myObj) { console.log(`key: ${key} value: ${myObj[key]}`);}// output// key: name value: Shuvo// key: tech value: javascript// key: hobby value: learning javascript// key: favFood value: beef steak!
3. Use Object.values() method. In this time you will get all the value of the remaining keys.
// way: 3 Object.values(myObj).forEach((value) => { console.log('value: ', value);});// output// value: Shuvo// value: javascript// value: learning javascript// value: beef steak!
4. Use Object.entries() method. It will return array of key and value
// way: 4 Object.entries(myObj).forEach((arr) => { console.log('arr: ', arr);});// output// arr: ["name", "Shuvo"]// arr: ["tech", "javascript"]// arr: ["hobby", "learning javascript"]// arr: ["favFood", "beef steak!"]
And that's it.Play with it more
Original Link: https://dev.to/naimahmedshuvo/how-to-loop-over-an-object-in-javascript-15pj
Share this article:
Tweet
View Full Article
Dev To
An online community for sharing and discovering great ideas, having debates, and making friendsMore About this Source Visit Dev To