Navigating through nested JSON objects using JavaScript

Trying to access and display a nested JSON object within the console.

This is the JSON data:

 {
  "currentUser": {
    "image": { 
      "png": "./images/avatars/image-juliusomo.png",
      "webp": "./images/avatars/image-juliusomo.webp"
    },
    "username": "juliusomo"
  },
  "comments": [
    {
      "id": 1,
      "content": "Impressive! Though it seems the drag feature could be improved. But overall it looks incredible. You've nailed the design and the responsiveness at various breakpoints works really well.",
      "createdAt": "1 month ago",
      "score": 12,
      "user": {
        "image": { 
          "png": "./images/avatars/image-amyrobson.png",
          "webp": "./images/avatars/image-amyrobson.webp"
        },
        "username": "amyrobson"
      },
      "replies": []
    },
    {
      "id": 2,
      "content": "Woah, your project looks awesome! How long have you been coding for? I'm still new, but think I want to dive into React as well soon. Perhaps you can give me an insight on where I can learn React? Thanks!",
      "createdAt": "2 weeks ago",
      "score": 5,
      "user": {
        "image": { 
          "png": "./images/avatars/image-maxblagun.png",
          "webp": "./images/avatars/image-maxblagun.webp"
        },
        "username": "maxblagun"
      },
      "replies": [
        {
          "id": 3,
          "content": "If you're still new, I'd recommend focusing on the fundamentals of HTML, CSS, and JS before considering React. It's very tempting to jump ahead but lay a solid foundation first.",
          "createdAt": "1 week ago",
          "score": 4,
          "replyingTo": "maxblagun",
          "user": {
            "image": { 
              "png": "./images/avatars/image-ramsesmiron.png",
              "webp": "./images/avatars/image-ramsesmiron.webp"
            },
            "username": "ramsesmiron"
          }
        }
        ]
        }
        }

Attempting to access replies with

console.log(data.comments.replies);
results in
Error: comments.replies is undefined

Code for accessing JSON:

fetch('./data.json', {
    method: 'GET',
    headers: {
        'Accept': 'application/json',
    },
})
    .then((response) => response.json())
        .then((data) => {
          console.log(data.comments.replies);
        
    })
     .catch((error) => {
         console.log(error);
     });

Need help looping through the array to display information in HTML.

Answer №1

Utilize the index for accessing replies

data.comments[index].replies

For instance:

data.comments[1].replies

const data = {
  "currentUser": {
    "image": {
      "png": "./images/avatars/image-juliusomo.png",
      "webp": "./images/avatars/image-juliusomo.webp"
    },
    "username": "juliusomo"
  },
  "comments": [{
      "id": 1,
      "content": "Impressive! Though it seems the drag feature could be improved. But overall it looks incredible. You've nailed the design and the responsiveness at various breakpoints works really well.",
      "createdAt": "1 month ago",
      "score": 12,
      "user": {
        "image": {
          "png": "./images/avatars/image-amyrobson.png",
          "webp": "./images/avatars/image-amyrobson.webp"
        },
        "username": "amyrobson"
      },
      "replies": []
    },
    {
      "id": 2,
      "content": "Woah, your project looks awesome! How long have you been coding for? I'm still new, but think I want to dive into React as well soon. Perhaps you can give me an insight on where I can learn React? Thanks!",
      "createdAt": "2 weeks ago",
      "score": 5,
      "user": {
        "image": {
          "png": "./images/avatars/image-maxblagun.png",
          "webp": "./images/avatars/image-maxblagun.webp"
        },
        "username": "maxblagun"
      },
      "replies": [{
        "id": 3,
        "content": "If you're still new, I'd recommend focusing on the fundamentals of HTML, CSS, and JS before considering React. It's very tempting to jump ahead but lay a solid foundation first.",
        "createdAt": "1 week ago",
        "score": 4,
        "replyingTo": "maxblagun",
        "user": {
          "image": {
            "png": "./images/avatars/image-ramsesmiron.png",
            "webp": "./images/avatars/image-ramsesmiron.webp"
          },
          "username": "ramsesmiron"
        }
      }]
    }
  ]
}

console.log(data.comments[1].replies)

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Fetching values from JSON object using Key in Angular

Here is the code snippet for the markup and component in question: new.component.html <a routerLink="{{sub.name}}" routerLinkActive="active">{{sub.name}}</a> old.component.ts data; this.route.params.subscribe((params:any) => {console.lo ...

Tips for using Angular's formatDate function to format dates

I am attempting to achieve a specific format using Angular's formatDate "2019-01-01T00:00:00Z" Here is the code I am using: formatDate( '2019-01-01', 'yyyy-MM-ddT00:00:00Z', 'en-US' ) The output I am getting is ...

Encountering a 403 error when attempting to upload files from Angular to a Micron

I have encountered an issue while attempting to upload multiple files to the Micronaut Rest API. The uploading process works seamlessly with Postman and Swagger in the Micronaut Rest API, but when using the Angular app, the POST method throws a 403 HTTP er ...

A guide on leveraging console.log in Next.js

I'm having trouble displaying the output of an API call using console.log. The issue is that nothing appears in the console (both in the browser and Visual Studio Code). The only console.log that seems to work is within the RouteStatus function, but i ...

Unable to access the uploaded file on the server

Scenario : When a user uploads an image and clicks on the "save" button, I successfully save the image on the server with 777 permission granted to the folder... https://i.sstatic.net/gcIYk.png Problem : However, when I try to open the image, it does n ...

Display complete information of the selected list in a modal window by clicking on it in PHP Yii

I recently started working with the Yii framework and encountered a challenge when trying to pass data from a list to a modal using AJAX. The modal is located within the same view as the list. Here's a snippet of my code: This is my view: <div id ...

Creating dynamic objects in C# using reflection

Is there a way to dynamically build a Payload for processing a Json file and adding values to the database, including only columns that are present in the Json? code payloadMessageContext.Update(new Payload { Id = 1, column1 = Attributes.Where(x =& ...

How to retrieve the chosen option from a drop-down menu created within a loop in a React application

I am seeking guidance on the best way to create multiple drop-down menus (<select>) using a loop, so that I can retrieve their selected values using a button. I have attempted to replicate what is currently in my code, hoping this information is suff ...

Guide to setting up a Node, Express, Connect-Auth, and Backbone application architecture for server-side development

As someone who primarily works on the client-side, I have recently ventured into the realm of server-side JavaScript. My initial plan for my first Node.js application involves a server-side setup that primarily serves an empty shell along with a plethora o ...

Utilize the client-side JavaScript file with ejs framework

Recently, I have been working on creating a website using Express and EJS. I discovered that using just one JavaScript file for all my EJS (view) files was causing issues. If I target a DOM element in one view page and it doesn't exist in another, I w ...

Guide on running a MySQL query in an asynchronous function in a Node.js application

Encountering some challenges while using MySQL in a node/express JS application. It seems that when trying to access the MySQL database within an asynchronous function, the code will 'skip over' the SQL query and run synchronously. This is the co ...

Troubleshooting a JavaScript project involving arrays: Let it pour!

I'm a beginner here and currently enrolled in the Khan Academy programming course, focusing on Javascript. I've hit a roadblock with a project called "Make it rain," where the task is to create raindrops falling on a canvas and resetting back at ...

How to retrieve TypeScript object within a Bootstrap modal in Angular

Unable to make my modal access a JavaScript object in the controller to dynamically populate fields. Progress Made: Created a component displaying a list of "person" objects. Implemented a functionality to open a modal upon clicking a row in the list. ...

How to retrieve the position of a recyclerview item and send the corresponding object when

I could really use some assistance right now, as I've hit a roadblock. To give you a brief overview, I have implemented a RecyclerView to display my parsed JSON data. Where I am currently stuck is figuring out how to obtain the position of an item in ...

Exploring BigQuery Audit Logs - identifying JSON metadata keys containing the '@' sign

When crafting queries in Log Explorer, we have the option to utilize the following syntax: protoPayload.metadata."@type"="type.googleapis.com/google.cloud.audit.BigQueryAuditMetadata" After successfully setting up a sink to store all l ...

It can be frustrating to have to refresh the page twice in order to see changes when utilizing the revalidate feature in Next

When I make the REST call to fetch data for my page using the code below: // src/app/page.js const Home = async () => { const globalData = await getGlobalData(); return ( <main'> <SomeComponent data={globalData} /> < ...

A guide to showcasing JSON data on a webpage using JavaScript

I am currently working on a SOAP WSDL invocation application in MobileFirst. The response I receive from the SOAP WSDL is in JSON format and is stored in the result variable. When trying to access the length of the response using result.length, I encounter ...

Tests are not visible to jasmine-node

Currently, I am utilizing jasmine-node and running it with the following command: node.exe path/to/jasmine_node --verbose path/to/my_file.js Despite successfully invoking Jasmine-node and receiving an error for incorrect paths, it appears that no tests a ...

What is the best way to handle this situation using Python?

My current task involves utilizing an API that provides a JSON string with a specific format: {u'inboxMessages': [{u'fromAddress': u'BM-2DBYkhiBZCyrBa8J7gFRGrFRSGqtHgPtMvwQ', u'toAddress': u'BM-2DC7SCTj2gzgrGgM ...

Adding a fresh element and removing the initial item from a collection of Objects in JavaScript

I'm working on creating an array of objects that always has a length of five. I want to push five objects initially, and once the array reaches a length of five, I need to pop the first object and push a new object onto the same array. This process sh ...