Looping Objects_ Object Keys, Values, and Entries

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.


If You Like This Page Then Make Sure To Follow Us on Facebook, G News and Subscribe Our YouTube Channel. We will provide you updates daily.
Share on:

NK Coderz is a Computer Science Portal. Here We’re Proving DSA, Free Courses, Leetcode Solutions, Programming Languages, Latest Tech Updates, Blog Posting Etc.

Leave a Comment