Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
May 21, 2022 08:44 am GMT

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:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To