Joe Wayne

I talk about technology, programming and development.

How to iterate through the properties of an object in JavaScript and print “key: value” to the console.

Here we will write a piece of javascript code that iterates through the properties of an object, printing in the browser console, and for each of them, the set “key: value”.

Iterating over an object’s properties is a common task in JavaScript, and it can be useful in many different scenarios. One way to do this is by using a loop for...in, which loops through each property of an object and performs an action for each one. In this article, we’ll see how to use a loop for...into print the “key:value” set to the browser console for each property of an object.

To start, let’s create a simple object with some properties:

const object = {
  name: 'John' ,
  age: 30 ,
  city: 'New York'
};

Now, let’s iterate over the object’s properties using the loop for…in. For each property, we’ll print to the console the key and the corresponding value, in the format “key: value”:

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

Here, we use the  ${chave}and syntax ${objeto[chave]}to create a string that contains the key and corresponding value of each property. The square bracket operator ( []) is used to access the property value using the key as the index.

When you run the above code in your browser console, the output will be something like:

nome: Jonh
idade: 30
cidade: New York

With this, we can iterate over the properties of an object in JavaScript and print “key: value” to the browser console for each of them.

Deixe um comentário

O seu endereço de e-mail não será publicado. Campos obrigatórios são marcados com *