Looping Objects_ Object Keys, Values, and Entries: Hello everyone, welcome to the nkcoderz.com website. In this article we will going to discuss about the Looping Objects_ Object Keys, Values, and Entries.
Looping Objects_ Object Keys, Values, and Entries
In JavaScript, you can use the Object.keys()
, Object.values()
, and Object.entries()
methods to loop through the keys, values, and key-value pairs of an object, respectively.
The Object.keys()
method returns an array of the object’s own enumerable properties, in the same order as that provided by a for…in loop.
Code For Object.keys() Method
let person = {
name: "John",
age: 30,
city: "New York"
};
let keys = Object.keys(person);
for (let key of keys) {
console.log(key);
}
Output
name, age, city
Code For Object.values() Method
The Object.values()
method returns an array of the object’s own enumerable property values, in the same order as that provided by a for…in loop.
let person = {
name: "John",
age: 30,
city: "New York"
};
let values = Object.values(person);
for (let value of values) {
console.log(value);
}
Output
John, 30, New York
Code For Object.entries() Method
The Object.entries()
method returns an array of the object’s own enumerable property [key, value] pairs, in the same order as that provided by a for…in loop.
let person = {
name: "John",
age: 30,
city: "New York"
};
let entries = Object.entries(person);
for (let entry of entries) {
console.log(entry);
}
Output
['name', 'John'], ['age', 30], ['city', 'New York']
Note that these methods were introduced in ECMAScript 2017, so you may need to include a polyfill for them if you need to support older browsers.
Conclusion
You can also use the for...in
loop to loop through object keys or forEach
method on Object.entries and also you can use the Object.entries
method with the for...of
loop to loop through the object’s key-value pairs.
If you liked this post Looping Objects_ Object Keys, Values, and Entries, then please share this with your friends and make sure to bookmark this website for more awesome content.