The Wayback Machine - https://web.archive.org/web/20240919170059/https://www.geeksforgeeks.org/how-to-access-and-process-nested-objects-arrays-or-json/
Open In App

How to access and process nested objects, arrays, or JSON ?

Last Updated : 22 Aug, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

JavaScript is used to bring interactivity to web pages. One of its features is handling data structures like Objects, Arrays, or JavaScript Object Notation (JSON). As data becomes more complex, it’s common to organize it into nested structures, where an object or array contains other objects, arrays, or JSON data within it. This article will help you to find the best methods for accessing and processing these nested structures in JavaScript.

Accessing and Processing Nested JavaScript Objects

Objects

A JavaScript Object is a container that holds the properties of the object in a key-value pair. The properties of an object are accessed using dot notation or square brackets notation. Objects that contain objects inside them are called nested or cascaded Objects. Accessing the value in nested objects can be done by consecutively applying dot or square bracket notation.

Approach 1: Accessing properties using dot notation

 Syntax:

objectName.property1Name.propert2Name...

The dot notation method checks for the property name inside the object and if it exists returns the value associated with that property inside the object. In case the returned value is an object, the sub-properties of that object can be reaccessed using the dot notation till we reach the required property value.

Example: Consider an object named person with a name and contact where a contact is an object consisting of properties such as phone, email, and address whereas an address is an object consisting of city and country properties. To access the city property using dot notation can be done as person.contact.address.city

JavaScript
let person = {
    name: "John",
    contact: {
        phone: "987-654-3210",
        email: "john123@xyz.com",
        address: {
            city: "Berlin",
            country: "Germany"
        }
    }
};

console.log(person.contact.email);              
console.log(person.contact.address.city);

Output
john123@xyz.com
Berlin

Approach 2: Accessing properties using square bracket notation

Syntax:

objectName[property1Name][propertyName2]...

The square bracket notation method checks for the property name inside the object by comparing the string value provided in square bracket notation to the properties of the object and if it exists, returns the value associated with that property inside the object. In case the returned value is an object, the sub-properties of that object can be accessed again in the same way till we reach the required property value.

Example: Consider an Object named person having properties name and contact where contact is an object consisting of properties phone, email, and address where address is an object consisting of properties namely city and country. To access the city property using square bracket notation can be done as a person[“contact”][“address”][“city”].

JavaScript
let person = {
    name: "Shaun",
    contact: {
        phone: "934-379-1420",
        email: "shaun2000@abc.com",
        address: {
            city: "London",
            country: "United Kingdom"
        }
    }
};

console.log(person["contact"]["email"]);             
console.log(person["contact"]["address"]["country"]);

Output
shaun2000@abc.com
United Kingdom

Accessing and Processing Nested JavaScript Arrays

Arrays

JavaScript array is a particular type of container that can hold more than one data of similar or different data types. Values in arrays can be accessed using an index (0-based indexing). Arrays that contain arrays inside them are called nested arrays or cascaded arrays. Accessing the value inside nested arrays can be done by consecutively using indexing in the array.

Syntax:

arrayName[index1][index2]...

Example: Consider an array of arrays namely arr. To access the value of the element at index 0 and inside that, at index 1 we use the following notation arr[0][1].

Consider the below code for accessing elements inside a nested array

JavaScript
const arr = [
    ["Rohit Sharma",45],
    ["Virat Kohli",18],
    ["M S Dhoni",7]
];

console.log(arr[0][1]);    
console.log(arr[2][0]); 

Output
45
M S Dhoni

Accessing and Processing Nested JSON Data

JavaScript Object Notation (JSON):

JSON is a lightweight data-interchange format that is used to send data between computers or servers. JSON is almost similar to JavaScript Objects except for the fact that the keys in JSON should compulsorily be a string and the value can be of any data type except a function, a date, and undefined. Nested or cascaded JSON are accessed in the same way as JavaScript Objects except for the fact that the key strings that contain spaces, dots, or brackets are only accessible using the JavaScript Object square bracket notation.

Approach 1: Accessing JSON properties using dot notation

Syntax:

jsonObject.property1Name.property2Name...

Like JavaScript Objects, JSON properties can also be accessed using the dot notation in the same manner. In this, the property name provided is compared to the properties of the JSON and if there is a match it returns the corresponding value. If the returned value is another JSON object then its further sub-properties can be accessed in the same manner.

Example: Consider a JSON named myJSON having properties Boss, Department, Department id, and employees array of JSON where the JSON inside employees array consists of name and age. To access the name of the employee at index 1, dot notation can be done as myJSON.employees[1].name and using square bracket notation as myJSON[“employees”][1][“name”].

JavaScript
let myJSON = {
    "Boss" : "John",
    "Department" : "Finance",
    "Department id": 3,
    "employees":[
        {
            "name":"Shaun",
            "age": 30
        },
        {
            "name":"Paul",
            "age" : 27
        }
    ]
};

console.log(myJSON.employees[1].name);     
console.log(myJSON["employees"][1]["name"]);

Output
Paul
Paul

Approach 2: Accessing JSON properties using square bracket notation 

Syntax:

jsonObject["property1Name"]["property2Name"]...

Like JavaScript Objects, JSON properties can also be accessed using the square bracket notation in the same manner. In this, the string of the property name provided is compared to the properties of the JSON and if there is a match i.e if the string matches any property string inside the JSON then it returns the corresponding value. If the returned value is another JSON object then its further sub-properties can be accessed in the same manner.

Example: Consider a JSON named myJSON having properties Boss, Department, Department id, and employees array of JSON where the JSON inside employees array consists of name and age. To access the Department id property dot notation cannot be used due to the space between them and hence it becomes compulsory to use square bracket notation to avoid any syntactical error. This can be done as myJSON[“Department id”]

JavaScript
let myJSON = {
    "Boss" : "John",
    "Department" : "Finance",
    "Department id": 3,
    "employees":[
        {
            "name":"Shaun",
            "age": 30
        },
        {
            "name":"Paul",
            "age" : 27
        }
    ]
};
   
console.log(myJSON["Department id"]);

Output
3

When working with nested data structures in JavaScript—whether they’re objects, arrays, or JSON—it’s important to choose the right method to access and manipulate data. Dot notation is concise and easy to use but is limited to keys that are valid identifiers. Square bracket notation is more flexible and allows for dynamic key access, making it suitable for complex or irregularly structured data.



Similar Reads

How to Remove Null Objects from Nested Array of objects in JavaScript ?
Removing null objects from the nested array of objects can be done by iterating over the array, filtering out the null objects at each level, and then applying a recursive approach to remove all the null objects. This makes sure that all the levels of the nested structure are checked and the null objects are removed. There are various approaches to
7 min read
How to Remove Multiple Objects from Nested Array of Objects in JavaScript ?
A nested array of objects is an array of arrays that contain multiple objects as their elements. Removing multiple objects from the nested array of objects in JavaSript can be accomplished in different ways as listed below: Table of Content Using filter() with some() methodUsing filter() with includes() methodUsing filter( ) with findIndex() method
7 min read
How to target Nested Objects from a JSON data file in React ?
Accessing nested JSON objects is similar to accessing nested arrays. Suppose we have a JSON object called person with a nested object 'address' , and we want to access the 'city' property from the address object. We can do this using dot notation like person.address.city. This notation allows us to directly access properties of nested objects withi
3 min read
Why does Vite create multiple TypeScript config files: tsconfig.json, tsconfig.app.json and tsconfig.node.json?
In Vite TypeScript projects you may have noticed three typescript configuration files, tsconfig.json, tsconfig.app.json, and tsconfig.node.json. Each file is used for a different purpose and understanding their use cases can help you manage TypeScript configurations for your project. In this article, you will learn about the three TypeScript config
6 min read
Convert JSON String to Array of JSON Objects in JavaScript
Given a JSON string, the task is to convert it into an array of JSON objects in JavaScript. This array will contain the values derived from the JSON string using JavaScript. There are two approaches to solving this problem, which are discussed below: Table of Content Using JSON.parse() MethodUsing JavaScript eval() MethodUsing Function ConstructorU
4 min read
How to Remove Null Objects from Nested Arrays in JavaScript ?
Javascript arrays are a very flexible container that can hold both elements or values. Nevertheless, with nested arrays, it is crucial for data management and cleaning. Replacing null objects is a frequent demand. Below are the methods to remove null objects from nested arrays in JavaScript: Table of Content Using Filter() MethodUsing Set MethodUsi
9 min read
How to Create Nested Arrays from a Nest of Arrays in JavaScript ?
Creating nested arrays from a nest of arrays in JavaScript involves organizing multiple arrays into a hierarchical structure, which is often useful for managing and representing complex data relationships. This process entails encapsulating arrays within other arrays to form multi-dimensional structures. Such nested arrays can represent various dat
3 min read
How to Iterate JavaScript Object Containing Array and Nested Objects ?
JavaScript provides us with several built-in methods through which one can iterate over the array and nested objects using the for...in loop, Object.keys(), Object.entries(), and Object.values(). Each method serves a distinct purpose in iterating over object properties, keys, and values which are explained as follows: Table of Content Using For...i
3 min read
What is the difference between Host objects and Native objects ?
In this article, we will learn about what are Host objects and Native objects, and their differences. JavaScript objects are broadly classified into 2 categories - native javascript objects and host javascript objects. Native objects: Native javascript objects are standard javascript objects which are provided by javascript itself. They are also kn
2 min read
How to create an array with multiple objects having multiple nested key-value pairs in JavaScript ?
In this article, we will learn to create an array with multiple objects having key-value pairs, we will use nesting which means defining another array in a pre-defined array with key-value pairs. Suppose we have several arrays of objects means containing various key-value pairs where keys are uniquely identified now we have to add these arrays to a
3 min read
How to Define Interfaces for Nested Objects in TypeScript ?
In TypeScript, defining interfaces for nested objects involves specifying the structure of each level within the object hierarchy. This helps ensure that the nested objects adhere to a specific shape or pattern. Here are step-by-step instructions on how to define interfaces for nested objects in TypeScript:Step 1: Identify the Nested Structures Det
2 min read
How to use splice on Nested Array of Objects ?
Using the splice() method on a nested array of objects in JavaScript allows you to modify the structure of the nested array by adding or removing elements at specified positions. Table of Content Accessing the nested array directlyUtilizing a combination of array methodsAccessing the nested array directlyThis approach directly accesses the nested a
2 min read
How to filter nested objects in JavaScript?
The filter() method creates a new array with all elements that pass the test implemented by the provided function. Below are the approaches used to filter nested objects in JavaScript: Table of Content Using filter() methodUsing some() method Method 1: Using filter() method Example: This approach uses the filter() method to filter the nested object
2 min read
How to Flatten Dynamically Nested Objects in Order in TypeScript ?
We are required to flatten a Typescript nested object that contains arrays and objects as children such that there should be no nested children left and everything should be at the same height. Example:Input: obj = { subject: "Computer Networks", students: { Jake: "USA" } }; Output: obj = { "subject": "Computer Networks", "students.Jake": "USA" }Ta
4 min read
How to read information from nested objects in DataTables ?
DataTables are a modern jQuery plugin for adding interactive and advanced controls to HTML tables for a webpage. It is a very simple-to-use plug-in with a variety of options for the developer’s custom changes as per the application need. The plugin’s features include pagination, sorting, searching, and multiple-column ordering. In this article, we
4 min read
Handling nested data objects using jQuery DataTables plugin
DataTables are a modern jQuery plugin for adding interactive and advanced controls to HTML tables for our webpage. It is a simple-to-use plug-in with many options for the developer's custom changes. The common features of DataTables are sorting, ordering, searching, and pagination. DataTables can easily read information for the columns from any nes
3 min read
Finding Objects using Lodash with Nested Properties
Finding objects by nested properties is a common task when dealing with complex data structures like deeply nested arrays or objects. Lodash, a popular JavaScript utility library, provides methods that simplify working with deeply nested data. PrerequisitesNode.jsNPMLodash LibraryInstall Lodash:Open your terminal and navigate to your project direct
2 min read
How to filter nested JSON object to return certain value using JavaScript ?
Given a collection that contains the detail information of employees who are working in the organization. We need to find some values from that nested collections of details. That collection is known as the JSON object and the information inside object are known as nested JSON object. Example 1: We create the nested JSON objects using JavaScript co
4 min read
How to add nested object to existing JSON using Postman ?
Postman has become a critical tool for developers around the world, particularly when dealing with JSON data. This article will guide you through the process of adding nested objects to an existing JSON using Postman, with a focus on the approaches and syntax involved. Table of Content Understanding JSON and Nested ObjectsThe Role of PostmanAdding
4 min read
How to read Array of Nested JSON Response in Postman ?
We know that the postman is the one who delivers the letters sent by your friends, colleagues, or relatives and acts as a bridge of communication. Here Postman refers to the development of API that acts as a bridge or communication between different programs. In other words, it is an API client, made for developing, testing, and management. You can
3 min read
Add Nested JSON Object in Postman
Postman is a helpful tool for testing APIs and working with JSON. It lets you add nested objects to existing JSON. JSON is a simple data format for both humans and machines. Postman also lets developers send requests and view responses, which is really useful for working with JSON data. These are the following approaches to add Nested JSON object:
2 min read
How to Traverse Array of Objects and Access the Properties in JavaScript?
Looping through arrays in JavaScript is straightforward because you can access elements using their indexes. However, when dealing with arrays of objects, the approach changes since objects consist of key-value pairs. In JavaScript, there are several methods to loop through objects, making it easy to access their keys and values. There are many way
4 min read
How to Access Nested Fields in React-Bootstrap-table ?
React-Bootstrap-Table provides a set of components and utilities that make it easy to create tables with features like sorting, filtering, pagination, and more. To access nested fields in React-Bootstrap-Table, you can use the dataField property of your column definitions to specify the path to the nested field in your data. Steps to Create React A
2 min read
How to access nested object in ReactJS ?
To access a nested object in react we can use the dot notation. But if we want to access an object with multi-level nesting we have to use recursion to get the values out of it. PrerequisitesReact JS NPM & Node.jsJavaScript ObjectApproachThe structure of an object in React JS can be nested many times and can get complicated quickly. If we want
2 min read
What is difference between JSON.parse() and JSON.stringify() Methods in JavaScript ?
JSON.parse() converts JSON strings to JavaScript objects, while JSON.stringify() converts JavaScript objects to JSON strings. JavaScript utilizes JSON for data interchange between servers and web pages. These methods enable easy data manipulation and transport in web development. JSON.parse() MethodJSON.parse() converts a JSON string to a JavaScrip
2 min read
How to use cURL to Get JSON Data and Decode JSON Data in PHP ?
In this article, we are going to see how to use cURL to Get JSON data and Decode JSON data in PHP. cURL: It stands for Client URL.It is a command line tool for sending and getting files using URL syntax.cURL allows communicating with other servers using HTTP, FTP, Telnet, and more.Approach: We are going to fetch JSON data from one of free website,
2 min read
Difference between package.json and package-lock.json files
In Node, package.json file contains the list of dependencies and scripts in a project while the package.lock.json specifies their respective versions to ensure consistent installations in different environments. In this article, we will learn the major differences between package.json and package.lock.json and their needs in Node. Table of Content
4 min read
Extract unique objects by attribute from array of objects
Given an array of objects and the task is to return the unique object by the attribute. Examples: Input: [ { name: 'Geeks', id: 10 }, { name: 'GeeksForGeeks', id: 10 }, { name: 'Geeks', id: 20 }, { name: 'Geeks', id: 10 } ]Output:[ { name: 'Geeks', id: 10 }, { name: 'GeeksForGeeks', id: 10 } ]Approach: Let's assume that name is an attribute that di
4 min read
Filter Array of Objects with Another Array of Objects in JavaScript
Filtering an array of objects with another array in JavaScript involves comparing and including objects based on specific criteria. Below are the approaches to filter an array of objects with another array of objects in JavaScript: Table of Content Using filter and includes MethodsUsing LoopingUsing reduce MethodUsing Set for Efficient FilteringUsi
3 min read
How to Convert Array of Objects into Unique Array of Objects in JavaScript ?
Arrays of objects are a common data structure in JavaScript, often used to store and manipulate collections of related data. However, there are scenarios where you may need to convert an array of objects into a unique array, removing any duplicate objects based on specific criteria. JavaScript has various methods to convert an array of objects into
8 min read
Article Tags :