Navigating through a JavaScript object array within another object

I am looking to iterate through a JavaScript object array

Here is my object response:

{
 "kind": "calendar#events",
 "etag": "\"p3288namrojte20g\"",
 "summary": "pedicura",
 "updated": "2019-05-01T14:25:51.642Z",
 "timeZone": "America/Argentina/Cordoba",
 "accessRole": "owner",
 "defaultReminders": [
  {
   "method": "popup",
   "minutes": 30
  }
 ],
 "nextSyncToken": "CJCLqtvE-uECEJCLqtvE-uECGAU=",
 "items": [
     // Items array content here...
 ]
}

I have attempted to loop through the items inside the body using different methods:

var dataStr = JSON.stringify(response);
var dataPrs = JSON.parse(dataStr);
var dataList = JSON.stringify(dataPrs.items);
dataStr = JSON.stringify(dataList);
dataPrs = JSON.parse(dataStr);
dataListPrs.forEach( console.log(dataPrs.htmlLink) );

and also:

cons items = data.items;
items.forEach(x => console.log(x.htmlLink))

and also:

var dataStr = JSON.stringify(response);
var dataPrs = JSON.parse(dataStr);
var body = dataPrs.body.items;
console.log("body", body);
const items = response.items;
console.log("items", items);
items.forEach(x => console.log(x.htmlLink));

however, I always encounter the issue where items is undefined

Answer №1

Based on the information you provided, I anticipate that the following lines of code will function correctly:

const items = response.items;
console.log("items", items);
items.forEach(x => console.log(x.htmlLink));

In my test, this code worked when I assigned the JSON data you supplied to the variable response. Therefore, it seems likely that response is not what you expect it to be during the execution of this code.

const response =  {"kind":"calendar#events","etag":"\"p3288namrojte20g\"","summary":"pedicura","updated":"2019-05-01T14:25:51.642Z","timeZone":"America/Argentina/Cordoba","accessRole":"owner","defaultReminders":[{"method":"popup","minutes":30}],"nextSyncToken":"CJCLqtvE-uECEJCLqtvE-uECGAU=","items":[{"kind":"calendar#event","etag":"\"3113441344690000\"","id":"hb6me2h********1dun5rs10","status":"confirmed","htmlLink":"https://www.google.com/calendar/event?eid=aGI2bWUyaGFvaGtqbWI4bXYxZHVuNXJzMTAgZTYyMXJtMD********Zw","created":"2019-05-01T14:12:08.000Z","updated":"2019-05-01T14:24:32.345Z","summary":"Prueba de: Pedicura en sala 2-x","description":"x-prueba de añadir masajes en sala 2 y notificar al manicura y a otra persona, fernanda?","creator":{"email":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="0661736f722b2b2b2b46616b676f6a2865696b">[email protected]</a>"},"organizer":{"email":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="5f3a7272722c666f293e341f382d302a2f713c3e333a313b3e2d7138303038333a713c3032">[email protected]</a>","displayName":"pedicura","self":true},"start":{"dateTime":"2019-05-08T21:00:00-03:00","timeZone":"America/Argentina/Buenos_Aires"},"end":{"dateTime":"2019-05-08T23:00:00-03:00","timeZone":"America/Argentina/Buenos_Aires"},"iCalUID":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="244c46124941164c450909090957151464434b4b4348410a474b49">[email protected]</a>","sequence":2,"attendees":[{"email":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="81e0ede4ebe0acacacace8f5c1e6ece0e8edafe2eeec">[email protected]</a>","responseStatus":"needsAction"},{"email":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="97fdbabababaf3d7f0faf6fefbb9f4f8fa">[email protected]</a>","responseStatus":"needsAction"}],"reminders":{"useDefault":true}},{"kind":"calendar#event","etag":"\"3113441378884000\"","id":"tv**0nbhkt**47la0k","status":"confirmed","htmlLink":"https://www.google.com/calendar/event?eid=dHZmOTQwbmJoaGJpbmVyYTExZW55bzh6OXggZTYyMXJtM*****","created":"2019-05-01T14:18:53.000Z","updated":"2019-05-01T14:24:49.442Z","summary":"Prueba de: Pedicura en sala 2-x","description":"x-prueba de añadir masajes en sala 2 y notificar al manicura y a otra persona, fernanda?","creator":{"email":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="3552405c4118181818755258545c591b565a58">[email protected]</a>"},"organizer":{"email":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="dfbaf2f2f2ace6efa9beb49fb8adb0aaaff1bcbeb3bab1bbbeadf1b8b0b0b8b3baf1bcb0b2">[email protected]</a>","displayName":"pedicura","self":true},"start":{"dateTime":"2019-05-07T21:00:00-03:00","timeZone":"America/Argentina/Buenos_Aires"},"end":{"dateTime":"2019-05-07T23:00:00-03:00","timeZone":"America/Argentina/Buenos_Aires"},"iCalUID":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="2f5b5949161b1f414d474402020202421b18433e1ccb17000434361500343*******04000636150c00190c54031f">[email protected]</a>","sequence":2,"attendees":[{"email":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="5938353c747474302d193e34383035773a3634">[email protected]</a>","responseStatus":"needsAction"},{"email":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="43296e6e2703242e222a2f6d202c2e">[email protected]</a>","responseStatus":"needsAction"}],"reminders":{"useDefault":true}},{"kind":"calendar#event","etag":"\"3113441503284000\"","id":"tqhje1kd*****0","status":"confirmed","htmlLink":"https://www.google.com/calendar/event?eid=dHFoamUxa2Q0MGFiNHAzd3VjbGVlOGRuODAgZTYyMX*****","created":"2019-05-01T14:25:51.000Z","updated":"2019-05-01T14:25:51.642Z","summary":"Prueba de","description":"prueba description","creator":{"email":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="01667468752c2c2c2c41666c60686d2f626e6c">[email protected]</a>"},"organizer":{"email":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="17723a3a3a642e2761767c5770657862673974767b727973766539707878707b723974787a">[email protected]</a>","displayName":"organizer name","self":true},"start":{"dateTime":"2019-04-26T21:00:00-03:00","timeZone":"America/Argentina/Buenos_Aires"},"end":{"dateTime":"2019-04-26T23:00:00-03:00","timeZone":"America/Argentina/Buenos_Aires"},"iCalUID":"unique-id-here","sequence":0,"attendees":[{"email":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="6845011c280f05090104460b0705">[email protected]</a>","responseStatus":"needsAction"},{"email":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="8da0ecf8e9cdeae0ece4e1a3eee2e0">[email protected]</a>","responseStatus":"needsAction"}],"reminders":{"useDefault":true}}]}
 
const items = response.items;
console.log("items", items);
items.forEach(x => console.log(x.htmlLink));

Answer №2

To extract the htmlLinks from the JSON object, use the forEach() method as demonstrated below:

let data =  {"kind":"calendar#events","etag":"\"p3288namrojte20g\"","summary":"pedicura","updated":"2019-05-01T14:25:51.642Z","timeZone":"America/Argentina/Cordoba","accessRole":"owner","defaultReminders":[{"method":"popup","minutes":30}],"nextSyncToken":"CJCLqtvE-uECEJCLqtvE-uECGAU=","items":[{"kind":"calendar#event","etag":"\"3113441344690000\"","id":"hb6me2h********1dun5rs10","status":"confirmed","htmlLink":"https://www.google.com/calendar/event?eid=aGI2bWUyaGFvaGtqbWI4bXYxZHVuNXJzMTAgZTYyMXJtMD********Zw","created":"2019-05-01T14:12:08.000Z","updated":"2019-05-01T14:24:32.345Z","summary":"Prueba de: Pedicura en sala 2-x","description":"x-prueba de añadir masajes en sala 2 y notificar al manicura and a otra persona, fernanda?","creator":{"email":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="7b1c0e120f565656563b1c161a121755181416">[email protected]</a>"},"organizer":{"email":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="16733b3b3b652f2660777d5671647963663875777a737872776438717979717a733875797b">[email protected]</a>","displayName":"pedicura","self":true},"start":{"dateTime":"2019-05-08T21:00:00-03:00","...
    
data['items'].forEach(getLinks);

function getLinks(item, index) {
  if(item.hasOwnProperty('htmlLink')){
     console.log(item.htmlLink)  
  }
}

Answer №3

When receiving a response from a Promise, consider iterating through response.data.items

Answer №4

After some investigation, I managed to crack the code - it was hidden within an episode of @Always Sunny and in a cryptic message from @Karl Galvez. Getting a hint from @Sandeep P's statement also played a key role as I had just implemented a .then method.

A huge thank you goes out to everyone who assisted me in solving this puzzle.

Answer №5

// this should function

var output = {
 "type": "calendar#events",
 "etag": "\"p3288namrojte20g\"",
 "summary": "pedicure",
 "updated": "2019-05-01T14:25:51.642Z",
 "timeZone": "America/Argentina/Cordoba",
 "accessRole": "owner",
 "defaultReminders": [
  {
   "method": "popup",
   "minutes": 30
  }
 ],
 "nextSyncToken": "CJCLqtvE-uECEJCLqtvE-uECGAU=",
 "items": [
  {
   "type": "calendar#event",
   "etag": "\"3113441344690000\"",
   "id": "hb6me2h********1dun5rs10",
   "status": "confirmed",
   "htmlLink": "https://www.google.com/calendar/event?eid=aGI2bWUyaGFvaGtqbWI4bXYxZHVuNXJzMTAgZTYyMXJtMD********Zw",
   "created": "2019-05-01T14:12:08.000Z",
   "updated": "2019-05-01T14:24:32.345Z",
   "summary": "Test: Pedicure in room 2-x",
   "description": "x-test to add massages in room 2 and notify the manicurist and another person, Fernanda?",
   "creator": {
    "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="7413011d0059595959341319151d185a171b19">[email protected]</a>"
   },
   "organizer": {
    "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="80e5adadadf3b9b0f6e1ebc0e7f2eff5f0aee3e1ece5eee4e1f2aee7efefe7ece5aee3efed">[email protected]</a>",
    "displayName": "pedicure",
    "self": true
   },
   "start": {
    "dateTime": "2019-05-08T21:00:00-03:00",
    "timeZone": "America/Argentina/Buenos_Aires"
   },
   "end": {
    "dateTime": "2019-05-08T23:00:00-03:00",
    "timeZone": "America/Argentina/Buenos_Aires"
   },
   "iCalUID": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="640c06520901560c054949494917555424030b0b0308014a070b09">[email protected]</a>",
   "sequence": 2,
   "attendees": [
    {
     "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="f3929f969992dededede9a87b3949e929a9fdd909c9e">[email protected]</a>",
     "responseStatus": "needsAction"
    },
    {
     "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="f399dededede97b3949e929a9fdd909c9e">[email protected]</a>",
     "responseStatus": "needsAction"
    }
   ],
   "reminders": {
    "useDefault": true
   }
  },
  {
   "type": "calendar#event",
   "etag": "\"3113441378884000\"",
   "id": "tv**0nbhkt**47la0k",
   "status": "confirmed",
   "htmlLink": "https://www.google.com/calendar/event?eid=dHZmOTQwbmJoa3Q3cnJvYjJsMW00N2xhMGsgZTYyMXJtM*****",
   "created": "2019-05-01T14:18:53.000Z",
   "updated": "2019-05-01T14:24:49.442Z",
   "summary": "Test: Pedicure in room 2-x",
   "description": "x-test to add massages in room 2 and notify the manicurist and another person, Fernanda?",
   "creator": {
    "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="fc9b899588d1d1d1d1bc9b919d9590d29f9391">[email protected]</a>"
   },
   "organizer": {
    "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="0f6a2222227c363f796e644f687d607a7f216c6e636a616b6e7d2168606068636a216c6062">[email protected]</a>",
    "displayName": "pedicure",
    "self": true
   },
   "start": {
    "dateTime": "2019-05-07T21:00:00-03:00",
    "timeZone": "America/Argentina/Buenos_Aires"
   },
   "end": {
    "dateTime": "2019-05-07T23:00:00-03:00",
    "timeZone": "America/Argentina/Buenos_Aires"
   },
   "iCalUID": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="add9dbcb94999dc3cfc5c680808080c0999ac1cc9dc6edcac2c2cac1c883cec2c0">[email protected]</a>",
   "sequence": 2,
   "attendees": [
    {
     "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="b5d4d9d0989898dcc1f5d2d8d4dcd99bd6dad8">[email protected]</a>",
     "responseStatus": "needsAction"
    },
    {
     "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="63094e4e0723040e020a0f4d000c0e">[email protected]</a>",
     "responseStatus": "needsAction"
    }
   ],
   "reminders": {
    "useDefault": true
   }
  },
  {
   "type": "calendar#event",
   "etag": "\"3113441503284000\"",
   "id": "tqhje1kd*****0",
   "status": "confirmed",
   "htmlLink": "https://www.google.com/calendar/event?eid=dHFoamUxa2Q0MG51M2Q3cGd2b2xlOGRqODAgZTYyMX*****",
   "created": "2019-05-01T14:25:51.000Z",
   "updated": "2019-05-01T14:25:51.642Z",
   "summary": "Test",
   "description": "x-test to add massages in room 2 and notify the manicurist and another person, Fernanda?",
   "creator": {
    "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="dfb8aab6abf2f2f2f29fb8b2beb6b3f1bcb0b2">[email protected]</a>"
   },
   "organizer": {
    "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="fc99d1d1d18fc5cc8a9d97bc9b8e93898cd29f9d909992989d8ed29b93939b9099d29f9391">[email protected]</a>",
    "displayName": "test",
    "self": true
   },
   "start": {
    "dateTime": "2019-04-26T21:00:00-03:00",
    "timeZone": "America/Argentina/Buenos_Aires"
   },
   "end": {
    "dateTime": "2019-04-26T23:00:00-03:00",
    "timeZone": "America/Argentina/Buenos_Aires"
   },
   "iCalUID": "tqh*****<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="55622532233a39306d313f6d6515323a3a3239307b363a38">[email protected]</a>",
   "sequence": 0,
   "attendees": [
    {
     "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="a38ecada593007">[email protected]</a>",
     "responseStatus": "needsAction"
    },
    {
     "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="143975617051532c0473775352270501444f7247514269714114">[email protected]</a>",
     "responseStatus": "needsAction"
    }
   ],
   "reminders": {
    "useDefault": true
   }
  }
 ]
};
var details = output.items;

if(details) {
    for (var itemsIter = 0; itemsIter < details.length; itemsIter++) {
        var detail = details[itemsIter];
        if(detail && detail.hasOwnProperty('htmlLink')) {
            console.log(detail.htmlLink);
        }
    }
}

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

There seems to be a hiccup in the JavaScript Console. It could potentially impact the functionality

Hey there, I'm encountering a strange issue in my IE 11 console. A JavaScript Console error has occurred. This may impact functionality. Whenever I try to run a for loop to create a list of elements within a ul tag 4000 times, the process stops at ...

Utilizing erb within a coffeescript file for modifying the background styling

Is there a way to change the background image of a div based on user selection from a dropdown menu? For instance, if the user picks "white" the background image becomes white, and for "red" it changes to red. I'm struggling with this in coffeescript ...

What steps should I take to address the issue of fixing the classname rather than using the

<div ng-class:"{{myclass}}" role="progressbar" aria-valuenow="{{roundedtotalPerformanceCount}}" aria-valuemin="0" aria-valuemax="100" ng-style="{'width' : ( totalPerformanceCount + '%' ) }"> {{roundedtotalPerformanceCou ...

Utilizing Nicknames in a JavaScript Function

I'm dealing with a function that is responsible for constructing URLs using relative paths like ../../assets/images/content/recipe/. My goal is to replace the ../../assets/images section with a Vite alias, but I'm facing some challenges. Let me ...

Implementing IBAN as the default option in Stripe's PaymentElement

The functionality of the react-stripe-js library's IbanElement includes various options such as supportedCountries and placeholderCountry: <IbanElement ... options={{ supportedCountries: ["SEPA"], placeholderCountry: "DE& ...

Keeping an HTML field constantly refreshed with dynamic content from Django

Imagine having two input fields along with an HTML paragraph displaying a Django value. Field A: <input ...> Field B: <input ...> <p>{{ sum }}</p> The goal is to have the sum update in real time, meaning that once both numbers ...

Submitting a Form with Multiple Pages

I'm encountering a challenge that I'm struggling to work through. Initially, we had a professional build our website, but since parting ways with the company, I've taken over site management. While I can handle basic tasks, I lack the expert ...

Preventing JSON data from being altered in AngularJS by creating a duplicate copy

It seems like there might be an issue with my implementation of AngularJS. I am trying to create a copy of a JSON object on page load, generate a form using the original data, and then compare the two JSON objects when the submit button is pressed to deter ...

My function seems to be functioning perfectly fine in Angular and Express, but for some reason, it's not working in Parse Cloud Code. What could

I am facing an issue with my code where it seems to be stuck. After testing it in both Angular and Express, I realized that the code is only progressing up to a certain point due to the requirement of the Master Key to edit the User table with new data. ...

The system is unable to retrieve the value of the property which is set as null

I'm trying to figure out how to store the input value of name_enter into the variable userName. However, every time I attempt this, I encounter the following console error: Uncaught TypeError: Cannot read property 'value' of null function ...

Troubleshooting Problem with MVC Ajax Requests

When working with an MVC view, I have a submit button that includes validation checks. If the validation fails, I return false to prevent the form from being submitted. In addition to standard validation, I also use an Ajax GET request to check for duplic ...

Guide to transforming a JsonArray into a Hashmap

I successfully obtained a jsonarray from a json string, however I am unsure of how to incorporate it into a Hashmap with a String indicating the type of cargo and an Integer representing the quantity. The provided string: "cargo":[ {"type":"Coals" ...

Leverage JSON data using props in React JS

Currently, my data is formatted in JSON and successfully populated into props known as foxFooterData. Upon inspecting the console.log result of foxFooterData.data, the following information is visible: https://i.sstatic.net/8htNG.png I am attempting to r ...

Creating a personalized Autocomplete feature using React Material-UI with the help of the renderInput method

I'm currently using a React Material UI Autocomplete component, similar to the one in the official documentation. For example, let's consider a list of countries: import * as React from 'react'; import Box from '@mui/material/Box& ...

Automatically updating div content using a static HTML page

Is there a way to refresh the content of an HTML div tag every 5 minutes without having to reload the entire page? <div id="pie"> <script src="index.js">// this script should be reloaded every 5 minutes </script& ...

Strange anomalies arising in frontend Apollo and GraphQL integration

Currently, I am working with nuxt.js and apollo. One issue I am facing is that when I click a button, it sends a request to the graphql server. The strange part is that the first time I click the button, everything works as expected. However, when I clic ...

What are the challenges associated with using replaceChild?

function getLatestVideos(url) { var http = new XMLHttpRequest(); http.open("GET", url, false); // false for synchronous request http.send(null); return http.responseText; } var videosText = getLatestVideos("https://www.googleapis.com/youtube/v3/se ...

Tips on updating a div with jQuery AJAX in my PHP script - help needed!

My jQuery call to PHP is functioning well. However, I am trying to figure out if it's possible to directly output the new content of a specific div from the PHP code using the echo statement. Is this achievable? In the past, I would return the update ...

Is there a way to set up ESLint for VSCode without relying on node or any

We have recently transitioned from the Atom editor to VSCode for teaching beginner JavaScript concepts. One challenge we are facing is that VSCode requires installation of node and then running npm install eslint, whereas in Atom, we could easily use the a ...

Creating a Paytm payment link using API in a React Native app without the need for a server

Suppose a user enters all their details and the total cost of their order amounts to 15000 rupees. In that case, the app should generate a Paytm payment link for this amount and automatically open it in a web view for easy payment processing. Any suggesti ...