In javascript object contain the key value pair properties and iterating over object is different from arrays . Objects can be iterated using for…in loops and Object.keys(), Object.values(), and Object.entries(). Let’s see how you can use each method:
1. using for...in
method
const person = { name: 'John', age: 30, occupation: 'Engineer' }; for(let key in persons){ console.log(`${person[key]} : ${key}`)
} //output // name: 'John', // age: 30, // occupation: 'Engineer'
2.Using Object.keys(): method
object.keys() is a javascript method which take object as argument and return array of keys
const person = { name: 'John', age: 30, occupation: 'Engineer' };
const Object_keys = Object.keys(person);
console.log(Object_keys)// [ 'name', 'age', 'occupation']```
we can use object.keys() to iterate over object
const person = { name: 'John', age: 30, occupation: 'Engineer' };
const Object_keys = Object.keys(person); //here first i have used Object_keys array which i got from Object.keys(person);
for(let i = 0 ; i<Object_keys.length;i++){ console.log(`${Object_keys[i]} : ${person[Object_keys[i]]}`);
} //here i have used Object_keys array which i got from Object.keys(person);
for(let keys of Object_keys){ console.log(`${keys} : ${person[keys]}`);
} // here i have just directly use object.key() method
for(let keys of Object.keys(person)){ console.log(`${keys}: ${person[keys]}`);
} // all three ways will give same output
name : John
age : 30
occupation : Engineer
3.Using Object.entries():
Object.entries() is a javascript method which take object as argument and return 2d array of key value pair
const person = { name: 'John', age: 30, occupation: 'Engineer' }; const Object_keyValue = Object.entries(person); //output
// [ [ 'name', 'John' ], [ 'age', 30 ], [ 'occupation', 'Engineer' ] ]
we can use Object.entries() to iterate over object
const person = { name: 'John', age: 30, occupation: 'Engineer' }; for (const [key, value] of Object.entries(person)) { console.log(`${key} : ${value}`);
} //output // name: 'John', // age: 30, // occupation: 'Engineer'
4. Using Object.values():
Object.values() returns an array of an object’s own enumerable property values. This can be useful if you’re only interested in the values and not the keys.
const myObject = { prop1: 'value1', prop2: 'value2', prop3: 'value3'
}; const values = Object.values(myObject); for (const value of values) { console.log(value);
}
Discover more from Coursity
Subscribe to get the latest posts sent to your email.