Exploring ways to retrieve nested values from JSON data using the Instagram API and Javascript

Trying to modify the script found at https://github.com/bigflannel/bigflannel-Instafeed in order to access Instagram photos on a website. Unfortunately, the script does not currently support displaying photo comments. I attempted to make modifications that would allow for this feature, but it resulted in an undefined value being returned. The script utilizes JavaScript to retrieve data from the API.

[
{
    "attribution": null,
    "tags": [

    ],
    "type": "image",
    "location": null,
    "comments": {
        "count": 2,
        "data": [
            {
                "created_time": "1389168592",
                "text": "Beautiful bridge!",
                "from": {
                    "username": "realwahyuputra",
                    "profile_picture": "http:\/\/images.ak.instagram.com\/profiles\/profile_180213154_75sq_1359089013.jpg",
                    "id": "180213154",
                    "full_name": "realwahyuputra"
                },
                "id": "628714182443349004"
            },
            {
                "created_time": "1389168601",
                "text": "also good views",
                "from": {
                    "username": "realwahyuputra",
                    "profile_picture": "http:\/\/images.ak.instagram.com\/profiles\/profile_180213154_75sq_1359089013.jpg",
                    "id": "180213154",
                    "full_name": "realwahyuputra"
                },
                "id": "628714254652486672"
            }
        ]
    },
    "filter": "Hefe",
    "created_time": "1350749506",
    "link": "http:\/\/instagram.com\/p\/RAqdlGyTSc\/",
    "likes": {
        "count": 0,
        "data": [

        ]
    },
    "images": {
        "low_resolution": {
            "url": "http:\/\/distilleryimage0.s3.amazonaws.com\/d87203101ad011e297b922000a1fa527_6.jpg",
            "width": 306,
            "height": 306
        },
        "thumbnail": {
            "url": "http:\/\/distilleryimage0.s3.amazonaws.com\/d87203101ad011e297b922000a1fa527_5.jpg",
            "width": 150,
            "height": 150
        },
        "standard_resolution": {
            "url": "http:\/\/distilleryimage0.s3.amazonaws.com\/d87203101ad011e297b922000a1fa527_7.jpg",
            "width": 612,
            "height": 612
        }
    },
    "users_in_photo": [

    ],
    "caption": {
        "created_time": "1350749545",
        "text": "From the office",
        "from": {
            "username": "bigflannel",
            "profile_picture": "http:\/\/images.ak.instagram.com\/profiles\/anonymousUser.jpg",
            "id": "240129684",
            "full_name": "Mike Hartley"
        },
        "id": "306431853609956969"
    },
    "user_has_liked": false,
    "id": "306431525321782428_240129684",
    "user": {
        "username": "bigflannel",
        "website": "",
        "profile_picture": "http:\/\/images.ak.instagram.com\/profiles\/anonymousUser.jpg",
        "full_name": "Mike Hartley",
        "bio": "",
        "id": "240129684"
    }
}];

Below is a function used to access data from the above JSON:

function imageCaptionText(timestamp) {
var text = 'Filter: ' + imageData[imageCount].filter + '<br />'
if (imageData[imageCount].caption != null) {
    text = text + 'Caption: ' +  imageData[imageCount].caption.text + '<br />';
}
if (imageData[imageCount].likes.count > 0) {
    text = text + 'Likes: ' + imageData[imageCount].likes.count + '<br />';
}
if (imageData[imageCount].comments.count > 0) {
    text = text + 'Comments: ' + imageData[imageCount].comments.count + '<br />';
}
if (imageData[imageCount].comments.data != null) {
    text = text + 'Comments Data: ' + imageData[imageCount].comments.data.text + '<br />';
}
if (imageData[imageCount].location != null) {
    text = text + 'Location: ' + imageData[imageCount].location + '<br />';
}
var date = new Date(1000*timestamp);
text = text + 'Date: ' + date.toLocaleString() + '<br />';
text = text + '<a href="' + imageData[imageCount].link + '">On Instagram</a><br />';
return text; }

Despite everything working well, the following code snippet returns an undefined value (an attempt to access comments data):

if (imageData[imageCount].comments.data != null) {
    text = text + 'Comments Data: ' + imageData[imageCount].comments.data.text + '<br />';
}

If there are any suggestions on how to resolve this issue, your assistance would be greatly appreciated. Thank you! :)

Answer №1

In order to access the actual text from the comments.data array, you need to reference it at

imageData[imageCount].comments.data[commentCount].text
. Here is an example of how you can achieve this:

if (imageData[imageCount].comments.data != null) {
    text = 'Comments Data:<br />';
    imageData[imageCount].comments.data.forEach(function(comment){
        text += comment.from.username + ': ' + comment.text + '<br />';
    });
}

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

How can you trigger a 'hashchange' event regardless of whether the hash is the same or different?

Having a challenge with my event listener setup: window.addEventListener('hashchange', () => setTimeout(() => this.handleHashChange(), 0)); Within the handleHashChange function, I implemented logic for scrolling to an on-page element whil ...

Passing props to children in the Next JS Layout component is a crucial aspect of

I recently came across a code snippet that effectively resolved my re-rendering issue in Next JS when switching pages. However, I am now faced with the challenge of sending props to the children component. In my layout.js file, I have managed to send props ...

What is the best way to parse this JSON using Jackson?

My JSON data is structured like this: { "summary":{ "somefield1":"somevalue1", "Twilio":{ "field1":"value1", "field2":"value2" }, "Tropo":{ "field1":"value1", "field2":"va ...

Using RTK Query to store data in a Firebase Realtime Database

Currently, I am facing an issue while trying to retrieve data from a Firebase Realtime Database using RTK Query. The code in this section is throwing an error because the return value is incorrect. If anyone has experience with this particular issue, I wou ...

Retrieving data from the server using Unity's deserialization function

After spending several hours attempting to deserialize data from my server for our high score system, I encountered an error: ArgumentException: JSON must represent an object type. Here is the code snippet showing how I am deserializing (scores is of t ...

Managing Multiple Operations in Angular Firestore

For the past few weeks, I've been grappling with the theory behind this issue. Despite scouring the internet for solutions, I haven't found anything truly helpful. So, I'm turning to the SO community for the first time. In my Firestore data ...

Using a custom jQuery function within an Angular component class

I have a custom query function that I wrote in a JavaScript file located under the source folder (/src/assets/inlineedit.js) of my Angular application. Here is the content of the file: $.fn.inlineEdit = function(replaceWith, connectWith) { $(this).ho ...

Is there a way to automatically recalculate the "Total Price" when the input values are adjusted?

Whenever I add an item to the cart, it gets appended to the row in the shopping cart, and the price adjusts accordingly. However, I'm having trouble getting the price to adjust whenever I change the input values (input type: "number"). I can't se ...

Facilitating the integration of both Typescript and JavaScript within a Node application

We are currently integrating Typescript into an existing node project written in JS to facilitate ongoing refactoring efforts. To enable Typescript, I have included a tsConfig with the following configuration: { "compilerOptions": { "target": "es6", ...

What is the best method to compare dates in JavaScript/JQuery to determine if one comes before the other?

I am completely new to JavaScript development and I need to accomplish the task below: I have 2 input tags containing 2 strings representing dates in the format 01/12/2014 (DAY/MONTH/YEAR). These input tags are used to search for objects with a date field ...

Utilizing AngularJS: Binding stateParams value to custom data within state objects

Following the guidelines here, I am setting a page title in my state object. $stateProvider .state('project', { url: '/projects/:origin/:owner/:name', template: '<project></project>', data : { pageTi ...

Poor quality picture captured with the use of the getUserMedia() Javascript function

Is there a way to improve the resolution of mobile phone camera screenshots taken with JavaScript's getUserMedia function? if (navigator.mediaDevices) { navigator.mediaDevices.getUserMedia({ video: { width: { min: 1280, }, heig ...

What is the best way to incorporate dynamic data from Firestore into a function using the `where()` method, while also utilizing the `snap.size` property to accurately count the total number of queries

I am facing an issue while trying to fetch data dynamically from firestore using a where() function. The specific error message I encountered is: TypeError: vaccines is not a function The user collection: [![enter image description here][1]][1] Here a ...

Utilizing Vue.js to initiate a server request with vue-resource

Seeking guidance on performing a server call using vue-resource. I'm unsure about how to set the header and send data via Vue.$http.post Vue.$http.post('http://url/', { email: 'foo', password: 'bar' }, { headers: { ...

Learning how to use Express.js to post and showcase comments in an HTML page with the help of Sqlite and Mustache templates

I am facing a persistent issue while trying to post new comments to the HTML in my forum app. Despite receiving various suggestions, I have been struggling to find a solution for quite some time now. Within the comments table, each comment includes attrib ...

Verify whether a specific value is present within a nested array in MongoDB

Looking to verify whether a value sent in a request already exists within an array associated with a particular User. The data structure is as follows: { "_id": "63233972df0f14076e027106", "firstName": "mako" ...

Changing the i18n locale in the URL and navigating through nested routes

Seeking assistance to navigate through the complexities of Vue Router configurations! I've dedicated several days to integrating various resources, but have yet to achieve successful internalization implementation with URL routes in my unique setup. ...

Having trouble with importing a variable in an Express application? You may encounter this error message: "Route.get() must

When trying to import requireSignin from the controllers/auth.js file into the routes/user.js file and adding it to the router.get('/user/:id', requireSignin, read); route, an error occurs: Error: Route.get() requires a callback function but r ...

Changes made to code within the node_modules directory do not appear in the browser

I encountered a bug in the vuejs-datepicker project on Github, prompting me to fork the repository. However, despite making changes to the forked project, these alterations are not reflected in my main project that relies on this dependency. Here's a ...

Exploring a one-dimensional nested array in order to make updates to the higher level nodes

I have a 1D nested array: nestedArr: [ { id: 1, parentId: null, taskCode: '12', taskName: 'Parent', duration: 0, assignee: '', crewCount: 0, startDate: null, endDate: null, dependencies: []}, { id: 2, parentId: 1, taskCo ...