Troubleshooting undefined object values in JavaScript

click here for the imageI am currently utilizing the quotes API in order to retrieve and display quotes. While I am able to print the entire object containing all information about the quote, I am encountering an issue where I cannot access the specific values within it - resulting in 'undefined' being logged in the console.

My expectation was to successfully extract individual values from objects when calling them, such as result.content. Below is the provided code snippet:

const url = "https://quotes15.p.rapidapi.com/quotes/random/";
const options = {
  method: "GET",
  headers: {
    "X-RapidAPI-Key": "api_key",
    "X-RapidAPI-Host": "quotes15.p.rapidapi.com",
  },
};
(async function main() {
  // You can use await inside this function block
  try {
    const response = await fetch(url, options);
    const result = await response.text();
    console.log(result);
    console.log(result.name);
  } catch (error) {
    console.error(error);
  }
})();

Answer №1

  1. Ensure you're parsing the response as json rather than text.

  2. The parsed object lacks a name property, but it does contain an originator property with a nested name property.

To get your code running smoothly, make these adjustments and unlock access to the remaining data using a similar approach.

const reply = await fetch(url, options);
const result = await reply.json();
console.log(result);
console.log(result.originator.name);

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

"Error message: Antd datepicker is throwing an error stating that date.clone/date.load is not a

I am working on a React app that has a checkbox to disable a datepicker. However, when I use the checkbox to disable it, I am unable to select any date. If I remove the checkbox and its function, there is no error. Currently, the error message I am getting ...

Storing a Vue JS component as a string in a variable and displaying it using that variable

I am currently working on a project where I need to implement the following code snippet: <template v-for="(element, k) in place.data.content"> <data_elements[element.name].component></data_elements[element.name].component> </te ...

Is there a way to stop a for-in loop within a nested forEach function in JavaScript?

I am facing a situation with nested loops for (var key in params) { if (Array.isArray(params[key])) { params[key].every(function(item) { let value = something(item.start, item.end); if (value === item.start || value == item.end) { ...

What is the process for activating and deactivating the scroll trigger within Material UI's useScrollTrigger module?

I'm currently working on setting up a survey page with Material UI in React. My goal is to have the survey questions appear when the user scrolls over them and disappear when they scroll out of view, similar to the behavior on this page. After some r ...

What is the best way to determine the width of a CSS-styled div element?

Is there a way to retrieve the width of a div element that is specified by the developer? For example, using $('body').width() in jQuery will provide the width in pixels, even if it was not explicitly set. I specifically need to access the width ...

The React forwardRef Higher Order Component is failing to provide a reference to the container element

I'm currently working on creating a higher order component (HOC) for closing an element when clicked outside of its space, known as a generic close on outside solution. In my understanding, this can be achieved using forwardRef and HOC implementation ...

Using Python, Scrapy, and Selenium to extract dynamically generated content from websites utilizing JavaScript

I am currently utilizing Python in combination with Selenium and Firefox to extract specific content from a website. The structure of the website's HTML is as follows: <html> <meta http-equiv="X-UA-Compatible" content="IE=EmulateIE8"> ...

Issue encountered when attempting to assign a value to an array property in Angular

Having trouble setting an array property in angular 6 using the following code: this.addupdate.roleids=this.selectedRole; An error is being thrown: ERROR TypeError: Cannot set property 'roleids' of undefined at AccessLevelComponent.pus ...

Encountering a compilation error when implementing ActionReducerMap in combination with StoreModule.forFeature

In my Angular project, the structure is organized as follows: /(root or repo folder) |_ projects |_ mylib (main library to be exported from the repo) |_ sample-app (created for testing 'mylib' project in other projects) To manage appli ...

You can definitely invoke a function within a React hook

This code snippet showcases a component utilizing Hooks in React Native import React, { useEffect, useState } from 'react'; import { StyleSheet, Text, View, TouchableOpacity, Animated } from 'react-native'; import CAStyles fro ...

Using next.js to fetch data can result in an endless loop of API

This specific code snippet is taken from the Next.js documentation and can also be accessed through the following link: https://nextjs.org/docs/app/building-your-application/data-fetching/fetching-caching-and-revalidating. However, when attempting to fetc ...

jquery disable document manipulation function

I need to make some updates to a simple function that involves the current textarea. $(document).on("keydown", updated_textarea_var, function (e) { // do stuff }); To achieve this, I tried disabling the previous function and running a new one w ...

Prevent form submission once all tasks have been finalized

Hey there, I've been racking my brain for hours trying to solve this issue... I'm looking to disable my form after it's been submitted to prevent multiple submissions. However, every method I try seems to disable the button but also interfe ...

5 steps to create a versatile function for activating attributes based on their values

Hey everyone! I was working on creating this calculator and I had different options to implement it, but I wanted to do it in a specific way. <form action=""> <label for="num1">Number A</label><br> <input type="number" na ...

Express.js post request not functioning properly

I am currently in the process of developing a discussion-based Node.js/Express app and I am focusing on creating a discussion page. I have been attempting to test if my discussion controller file is properly linked, but for some reason every time I click t ...

Navigating through nested data in React TypeScript can be accomplished by accessing the nested data

How can data in a nested interface like the one shown below be accessed in React TypeScript? export interface School { prices: Array<{ state: { response_header?: { school_type_opportunities?: Array<{ benefit_type_opportunity?: st ...

Iterating through object using jQuery

I'm facing an issue with iterating through a JSON object for the first time. The JSON is structured like this: { "response": { "2012-01-01": { "Available": 99, "Variations": [ { ...

Utilizing dynamically loaded JSON data in Vue 3 templates

Within my Vue3 view, I encounter the need to dynamically import JSON data based on the browser URL. This means that the JSON filename will vary depending on the URL, such as domain.com/canada utilizing canada.json and domain.com/usa utilizing usa.json, all ...

Execute a specific function when the Node.js countdown reaches zero

I am currently working on a web application and I need to incorporate a new function. This function will display a table containing certain results when a user submits a request. If the user does not submit anything, it will show different results as tim ...

Success callbacks parsed from AJAX requests

When dealing with a Backbone object and making an AJAX call to save it, I often wonder about the different ways the success callback can be handled. Sometimes, I see a generic success: function (data) { console.log(data); Other times, it's more spec ...