javascript loop trough object example
Here's an example of how to loop through an object in JavaScript:
**Example 1: Using a `for...in` loop**
javascript
const person = {
name: 'John',
age: 30,
city: 'New York'
};
for (let key in person) {
console.log(`Key: ${key}, Value: ${person[key]}`);
}
// Output:
// Key: name, Value: John
// Key: age, Value: 30
// Key: city, Value: New York
**Example 2: Using a `for...of` loop (ES6+)**
Note: `for...of` is not supported in older browsers, use the next example if you need cross-browser compatibility.
javascript
const person = {
name: 'John',
age: 30,
city: 'New York'
};
for (let [key, value] of Object.entries(person)) {
console.log(`Key: ${key}, Value: ${value}`);
}
// Output:
// Key: name, Value: John
// Key: age, Value: 30
// Key: city, Value: New York
**Example 3: Using a `for...in` loop with `hasOwnProperty()`**
This example shows how to use `hasOwnProperty()` to avoid iterating over inherited properties.
javascript
const person = {
name: 'John',
age: 30,
city: 'New York'
};
for (let key in person) {
if (person.hasOwnProperty(key)) {
console.log(`Key: ${key}, Value: ${person[key]}`);
}
}
// Output:
// Key: name, Value: John
// Key: age, Value: 30
// Key: city, Value: New York
**Example 4: Using `Object.keys()` and a `forEach()` loop**
This example uses the spread operator (`...`) to convert an array of keys into an actual array.
javascript
const person = {
name: 'John',
age: 30,
city: 'New York'
};
let keys = [...Object.keys(person)];
keys.forEach(key => {
console.log(`Key: ${key}, Value: ${person[key]}`);
});
// Output:
// Key: name, Value: John
// Key: age, Value: 30
// Key: city, Value: New York
These are just a few examples of how to loop through an object in JavaScript. You can choose the method that best fits your needs!