How to Get All Properties of an Object in Java

How to loop through objects keys and values in Javascript?

A common problem faced by programers is looping over an enumerable dataset. This data can come in the form of arrays, lists, maps or other objects. In this article we will deal with this problem and learn 4 ways to loop through objects using javascript to retrieve multiple key-value pairs.

How to loop through objects in JavaScript?

The various methods that can be used to loop through objects in JavaScript are:

  1. Using a for...in loop
  2. Object.keys method
  3. Object.values method
  4. Object.entries method

Continue reading to learn more about the various methods.

Table of Contents

  • Introduction to undefined and null values in Javascript
  • Methods to loop through objects using javascript
  • Parting words
  • Other Related Concepts

Introduction to looping through objects using javascript

If you have an array that is considered to be an object in javascript, you can't loop through the array using map(), forEach(), or a for..of loop.

You will get errors:

          const items = {     'first': new Date(),     'second': 2,     'third': 'test' }                  

map() will give you TypeError: items.map is not a function:

          items.map(item => {})                  

forEach() will give you TypeError: items.forEach is not a function:

          items.forEach(item => {})                  

for..of will give you TypeError: items are not iterable:

          for (const item of items) {}                  

Methods to loop through objects using javascript

for...in Loop

The most straightforward way to loop through an object's properties is by using the for...in statement. This method works in all modern and old browsers including Internet Explorer 6 and higher.

Here is an example that uses the for...in loop to iterate over an object:

          const user = {      name: 'John Doe',      email: '[email protected]',      age: 25,      dob: '08/02/1989',      active: true };  // iterate over the user object  for (const key in user) {      console.log(`${key}: ${user[key]}`); }  // name: John Doe  // email: [email protected]  // age: 25  // dob: 08/02/1989  // active: true                  

One problem in using the for...in method is that it loops through the properties in the prototype chain as well. Since the objects in JavaScript can inherit properties from their prototypes, the for...in statement will loop through those properties as well.

To avoid this problem, you have to explicitly check if the property belongs to the object by using the hasOwnProperty() method:

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

To overcome this hassle, later in ES8, two other methods were added, Object.entries() and Object.values(). These methods convert the object into an array and then use array looping methods to loop over that array.

Object.keys() Method

Before ES6, the only way to loop through an object was through using the for...in loop. The Object.keys() method was introduced in ES6 to make it easier to loop over objects.

It takes the object that you want to loop over as an argument and returns an array containing all properties names (or keys).
After which you can use any of the array looping methods, such as forEach(), to iterate through the array and retrieve the value of each property.

Here is an example:

          const courses = {     java: 10,      javascript: 55,      nodejs: 5,      php: 15 };  // convert object to key's array  const keys = Object.keys(courses);  // print all keys  console.log(keys);  // [ 'java', 'javascript', 'nodejs', 'php' ]  // iterate over object  keys.forEach((key, index) => {     console.log(`${key}: ${courses[key]}`); });  // java: 10  // javascript: 55  // nodejs: 5  // php: 15                  

Object.values() Method

The Object.values() method was introduced in ES8 and it works opposite to that of Object.key(). It returns the values of all properties in the object as an array. You can then loop through the values array by using any of the array looping methods.

Let us look at an example:

          const animals = {     tiger: 1,      cat: 2,      monkey: 3,      elephant: 4 };  // iterate over object values  Object.values(animals).forEach(val => console.log(val));  // 1 // 2 // 3 // 4                  

Object.entries() Method

The Object.entries(), an other ES8 method can be used for traversing an array. . Object.entries() outputs an array of arrays, with each inner array having two elements. The first element being the property and the second element is the value.

Here is an example:

          const animals = {     tiger: 1,      cat: 2,      monkey: 3,      elephant: 4 };  const entries = Object.entries(animals); console.log(entries);  // [ [ 'tiger', 1 ],  //   [ 'cat', 2 ],  //   [ 'monkey', 3 ],  //   [ 'elephant', 4 ] ]                  

To loop over the array returned by Object.entries(), you can either use the for...of loop or the forEach() method as shown below:

          // `for...of` loop for (const [key, value] of Object.entries(animals)) {     console.log(`${key}: ${value}`); }  // `forEach()` method  Object.entries(animals).forEach(([key, value]) => {     console.log(`${key}: ${value}`) });                  

Parting Words

We have briefly seen about 4 different ways to loop through objects in javascript. If you are using old browsers, for...in is still a good option, otherwise, you can use any of the latest methods discussed above.

How to Get All Properties of an Object in Java

Source: https://flexiple.com/loop-through-object-javascript/

0 Response to "How to Get All Properties of an Object in Java"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel