Disclaimer: TubeMint is fully funded by its readers, we recommend hightly rated affiliate products and services and when you buy them through our links, we get commission at no extra cost to you. Thanks for you support!

JavaScript Object Loops and Iteration

In this post I going to show you how to loop and iterate object keys and values from JavaScript Objects. I am going to use for of and for in loops and Object.key() and Object.entries() to demonstrate the example code.

JavaScript Object

Here is the JavaScript Object that I’ll be using throughout the post.

const Car = {
	model: "2000",
	make: "Ford",
	seats: "6",
	color: "White"

}

Using for of and Object.entries()

The following code demonstrate how you can print out JavaScript Object keys and values using for of, Object.entries and array destructure.

for(const [k,v] of Object.entries(Car)){
	console.log(k+" "+v);
}

// model 2000
// make Ford
// seats 6
// color White

Using for of and Object.keys()

The following code demonstrate how you can print out JavaScript Object keys with the help of for of and Object.keys().

for(const key of Object.keys(Car)){
	console.log(key);
}

// model 
// make 
// seats 
// color

Using forEach and Object.entries()

You can use following code to print out JavaScript Object keys and values, which uses forEach loop and Object.entries().

Object.entries(Car).forEach(([k,v])=>{
	console.log(`${k}:  ${v}  `)
} )

// model:  2000  
// make:  Ford  
// seats:  6  
// color:  White

Using forEach and Object.keys()

The code below will print out JavaScript Object keys only and that uses forEach loop and Object.keys().

Object.keys(Car).forEach((k)=> console.log(k))

// model
// make
// seats
// color

Using for in loop

Here is another way to loop through JavaScript Objects and print out key, value pair, that uses for in loop.

for (const k in Car) {
	console.log(`${k} : ${Car[k]}`);
}

// model : 2000
// make : Ford
// seats : 6
// color : White

That’s it for this post, please let other know which one did you like the most so that people can engage and learn more.

JavaScript Practical Course

If you want to become a JavaScript Developer; do not waste your time and money: try this JavaScript Course that teaches your JavaScript, NodeJS, ExpressJS, MongoDB at a very affordable price. View the JS course here before you sign up.

Techbuyer

1 thought on “JavaScript Object Loops and Iteration”

Leave a Reply