Skip to main content
Iterating-over-a-JavaScript -Object

Exploring JavaScript Objects and JSON Iteration

This tutorial delves into the world of JavaScript objects, exploring JSON object types and iteration loops, presenting various techniques for iterating over JavaScript objects, and discussing their use cases and benefits.

In JavaScript, objects are a fundamental data structure that allows you to store and organize data in key-value pairs.

What’s Javascript Object

JavaScript objects are an essential data structure that allows for storing and organizing data in key-value pairs. The key is typically a string or symbol, and the value can be of any data type, including objects, arrays, functions, or primitive values like numbers and strings.

Understanding JSON

JSON (JavaScript Object Notation) is a widely used data format for exchanging information between web services and applications. Its popularity stems from the multitude of JavaScript frameworks available that facilitate the creation of feature-rich user interfaces.

Types of JSON Objects

This tutorial help to understand the different type of JSON objects like single JSON object, array JSON data and how to process these JSON objects in your application using jQuery and JavaScript, normally we are using four type JSON object.

We can have :

  1. Single JSON Object: This refers to a standalone JSON object containing key-value pairs. Each key-value pair represents a property of the object.
  2. Array of JSON Objects: An array JSON data structure consists of multiple JSON objects indexed by integers. It allows for storing a collection of related objects, making it convenient for handling multiple data entries.
  3. Multiple JSON Objects: In this scenario, multiple individual JSON objects coexist, typically within an array. Each JSON object holds its own set of properties, providing a way to organize distinct pieces of data.
  4. Nested JSON Objects with String Key Index: Nested JSON objects employ string keys for indexing. This hierarchical structure allows for organizing complex data relationships and creating nested data structures.

You can also check other tutorials of JSON Object,

Option 1: A single JSON Object

The single JSON object is the simplest and most straightforward type. It consists of a collection of key-value pairs enclosed in curly braces {}. Each key is a string that acts as an identifier for the corresponding value. The value can be of any data type supported by JSON, such as strings, numbers, booleans, null, arrays, or even nested objects.

var jsonObj = {
	"name" : "Adam",
	"age" : "30",
	"gender" : "male"
};

Single JSON objects are commonly used for representing individual entities or records in a dataset. You can access the above JSON object data using key-value notation like below:

 console.log(jsonObj.name);
 console.log(jsonObj.age);

Option 2: Array of JSON Objects

A JSON object array is an array of JSON objects. It is denoted by enclosing multiple JSON objects in square brackets [], with each object separated by a comma. Each object in the array can have its own unique set of key-value pairs.

Sometimes, We will get a JSON object in the array from the response that time we need to iterate on the object’s array and drill down to get a single object, after that you can apply option 1 formula to get object value.

var jsonObjs = [{
    "name" : "adam",
    "age" : "30",
    "gender" : "male"
},
{
    "name" : "Roy",
    "age" : "21",
    "gender" : "male"
}];

JSON object arrays are commonly used to store lists of related data, such as a list of users, products, or articles.

You can access the above json object array data using forEach function. We will iterate on arrays and then access single object value using key as like below,

jsonObjs.forEach(function(obj) {
  console.log(obj.name);
  console.log(obj.age);
});

Option 3: Multiple JSON Objects

Multiple JSON objects refer to the scenario where individual JSON objects coexist, usually within an array. Each JSON object maintains its own set of properties, allowing for the organization of distinct pieces of data. This type of JSON object is commonly used when handling multiple independent data entities.

var jsonObjs = {"adam" : {
    "age" : "30",
    "gender" : "male"
},
"Roy" : {
    "age" : "21",
    "gender" : "male"
}};

We can access data as like below:

for (var key in jsonObjs) {
  if (jsonObjs.hasOwnProperty(key)) {
	console.log(key);
	console.log(jsonObjs[key].gender);
  console.log(jsonObjs[key].age);
  }
}

Option 4: Nested JSON Objects with String Key Index

Nested JSON objects are JSON objects that contain other JSON objects as their property values. This allows for hierarchical and structured data representation. In other words, objects are nested within other objects.

var jsonObjs = {
  "person1": {
    "name": "Adam",
    "age": 30,
    "address": {
      "street": "123 Main St",
      "city": "New York"
    }
  },
  "person2": {
    "name": "Jane Smith",
    "age": 25,
    "address": {
      "street": "456 Elm St",
      "city": "Los Angeles"
    }
  }
}

We can get JSON objects in an array with an index (ie. index 0,1) or nested JSON object with a string key.

Nested JSON objects are useful when dealing with complex data structures where properties have multiple attributes

I am using JavaScript for() function to iterate on nested JSON object, first we will iterate on nested json data to find json object then access single object value using key, like below,

for (var key in jsonObjs) {
  if (jsonObjs.hasOwnProperty(key)) {
	console.log(key);
	console.log(jsonObjs[key].name);
  console.log(jsonObjs[key].age);
  }
}

Output:

person1
Adam
30
person2
Jane Smith
25

Exploring JSON Iteration Techniques

There are following different techniques for iterating over them, including JSON objects.

Iterate Using for...in Loop

The for...in loop is a built-in JavaScript construct that iterates over the enumerable properties including properties inherited from the prototype chain of an object. It allows us to access each property key and its corresponding value. Here’s an example:

const person = { name: 'Adam', age: 30, city: 'Denver' };

for (let key in person) {
  console.log(key, obj[key]);
}

in the above code, for...in loop iterates over all enumerable properties of the person object, logging each property’s key-value pair.

Output:

name
 Adam
age
 30
city
 Denver

Iterate Using Object.keys()

The Object.keys() method returns an array containing the keys of the object’s own enumerable properties. Then you can iterate over the keys using a for...of loop or any array iteration method.

const person = { name: 'Adam', age: 30, city: 'Denver' };

for (let key of Object.keys(person)) {
  console.log(key, obj[key]);
}

In the above example, we obtain an array of keys using Object.keys(person) and iterate over it using a for loop. We can then access the corresponding values using the key-value notation.

Output:

Name Adam
age
 30
city
 Denver

Object.entries()

The Object.entries() method returns an array of the object’s own enumerable properties as an array of [key, value] pairs. This allows you to iterate directly over both the keys and values of the object.

const person = { name: 'Adam', age: 30, city: 'Denver' };

for (let [key, value] of Object.entries(person)) {
  console.log(key, value);
}

In this example, we use Object.entries(person) to obtain an array of key-value pairs and iterate over it. The destructuring assignment [key, value] allows us to extract the key and value from each pair.

Output:

name
Adam
age
30
city
Denver

Conclusion

In this article, we have explored various types of JSON objects and examined different techniques for iterating over JavaScript objects. We have seen how the for...in loop, Object.keys(), and Object.entries() provide powerful methods for traversing object properties and conducting operations on them.

Leave a Reply

Your email address will not be published. Required fields are marked *